APIから取得したデータを画面に表示する

こんにちは。oda@エンジニア1年目です。

前回の記事では、json形式で取得したデータを返すAPIを作成しました。

今回は、この取得したデータをAjaxで画面に表示させてみます。

(以下、Rails 6.1.6を使用しています。)

画面の準備

画面を表示させるために次のファイルを準備します。

controllers/students_controller.rb

class StudentsController < ApplicationController
  def index
  end
end

routes.rb

Rails.application.routes.draw do
  resources :students, only: [:index] # ここを追加
  namespace :api, format: 'json' do
    resources :students, only: [:index]
  end
end

views/students/index.html.erb

<div class="title">
  <span>生徒一覧</span>
  <button id="display-btn">表示</button>
</div>
<table>
  <tr>
    <th>1年生</th>
    <th>2年生</th>
    <th>3年生</th>
  </tr>
  <tr>
    <td><ul id='1st-grade'></ul></td>
    <td><ul id='2nd-grade'></ul></td>
    <td><ul id='3rd-grade'></ul></td>
  </tr>
</table>

ブラウザ上では次ように表示されています。(CSSは割愛)

Ajaxで作成したAPIにリクエストを送る

それでは、前回作成した以下の生徒が、表示ボタンを押すと各学年ごとに表示されるようにしていきます。

id(integer) name(string) grade(integer)
1 Alice 3
2 Bob 1
3 Charlotte 1
4 Daniel 2
5 Edward 3

今回はjQueryのajaxメソッドを使って、作成したAPIにリクエストを送るので、次のとおりjsファイルを作成します。

students.js

$(function () {
  $('#display-btn').on('click', function() {
    const res = $.ajax({
      url: '/api/students',
      type: 'GET',
      dataType: 'json',
    });
    res.done((res) => {
            console.log('読み込みに成功しました');
      res.students.forEach((student) => {
        switch(student.grade) {
          case 1:
            $('#1st-grade').append(`<li>${student.name}</li>`);
            break;
          case 2:
            $('#2nd-grade').append(`<li>${student.name}</li>`);
            break;
          case 3:
            $('#3rd-grade').append(`<li>${student.name}</li>`);
            break;
        }
      });
    });
    res.fail(() => {
      console.log('読み込みに失敗しました')
    });
  });
});

上記のresには、APIからjson形式で返ってきた全生徒のデータが入っています。

この全生徒のデータをforEachメソッドを使って1人ずつ取り出し、各学年の列に名前を表示させるようにしています。

先ほどの表示ボタンを押すと、画面はこうなります。

さいごに

今回作成したプログラムは非常にシンプルなものではありますが、一つ一つ動作を確認しながら一から自分で作成することで、理解を深めることができました。

これからも自分でプログラムを作成し理解を深めることで、業務で扱うプログラムの理解も深めていきたいと思います!

最後までご覧いただきありがとうございました!