LoginSignup
0
1

More than 3 years have passed since last update.

$.getメソッドを使って非同期通信でapiを表示する

Posted at

Ajaxでapiを表示する

動的なページで自作したapiを静的なフロントのページで表示させる必要があったので備忘録として残します。

laravelでapiの作り方

動的なページ側での話。
Http/Controllers/APIにapi用のコントローラーを作成。
今回はFAQのAPIを作る。

FAQAPIController
class APIFAQController extends Controller
{
    public function index(Request $request){
        $faq = Faq::all();
        header("Access-Control-Allow-Origin: *");
        return Response::json($faq);
    }
}

routeのapi.phpにapi用のルートを設定する

//FAQ API
Route::get('/index','API\APIFAQController@index')->name('api.index');

これでURLに api/index にアクセスするとjsonでレスポンスが返ってくる
postmanで確認するとapiの中身が確認できる。

apiの受け取った通信データの表示方法

ここから静的ページサイトでどうやって表示させるかという話。
$.getメソッドを使って通信データを取得できる
$.get('apiのurl',function(data))
functionの中のdataが引数で通信データを受け取ることができる。

index.html
 $.get('apiurl',function(data){
   //処理を書く
 })

あとは処理を書いていけばよい

index.html
<script>
  $(function(){
        $.get('https://faq.com/api/index', function(data){
            for(var i=0; i<data.length; i++){
                var question = data[i].question;
                var answer = data[i].answer;
                console.log(question);
                console.log(answer);
            }
</script>

こんな感じです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1