4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ElixirでAPIを作って「jQuery + getJSON」で取得する

Last updated at Posted at 2024-09-10

目的

  • ElixirでAPIを作成
  • getJSONの検証

Elixirでプロジェクト作成

$ mix phx.new jquery_getjson_experiment --database sqlite3
$ cd jquery_getjson_experiment
$ mix ecto.create

ElixirでAPI作成

$ mix phx.gen.json Accounts User users name:string

router.exにAPIのパスを追加

lib/jquery_getjson_experiment_web/router.ex
defmodule JqueryGetjsonExperimentWeb.Router do
  # 〜省略〜
+  scope "/api", JqueryGetjsonExperimentWeb do
+    pipe_through :api
+
+    resources "/users", UserController, except: [:new, :edit]
+  end
  # 〜省略〜
end

migrate実行

$ mix ecto.migrate

Elixirでデータ入力画面作成(LiveView)

$ mix phx.gen.live Accounts User users name:string

router.exにLiveViewのパスを追加

lib/jquery_getjson_experiment_web/router.ex
defmodule JqueryGetjsonExperimentWeb.Router do
  # 〜省略〜
  scope "/", JqueryGetjsonExperimentWeb do
    pipe_through :browser

+   live "/users", UserLive.Index, :index
+   live "/users/new", UserLive.Index, :new
+   live "/users/:id/edit", UserLive.Index, :edit

+   live "/users/:id", UserLive.Show, :show
+   live "/users/:id/show/edit", UserLive.Show, :edit

    get "/", PageController, :home
  end
  # 〜省略〜
end

不要ファイルを削除

jquery_getjson_experiment/priv/repo/migrations/
に 「日時_create_users.exs」のファイルが2つできている
新しい方を消す

これは、APIとLiveView作ったときに「usersテーブル」の定義として作られている
同じ定義の為余分になる

同じテーブル定義で作った為です

htmlディレクトリを開放

lib/jquery_getjson_experiment_web.ex
defmodule JqueryGetjsonExperimentWeb do
  # 〜省略〜
- def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
+ def static_paths, do: ~w(assets fonts images favicon.ico robots.txt html)
  # 〜省略〜
end

jQuery + getJSONの検証ファイルを作成

priv/static/html/test.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <script  src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function(){
            // DOMがロード時に実行
            $("#title").text("jquery getJSON テスト");

            // /api/usersからデータを取得
            $.getJSON("/api/users", function(json){
                for(rowNo in json.data) {
                    // 取得後に1件ごとdivの中に追加する
                    $("#jsontext").append("<p>" + json.data[rowNo].name + "</p>");
                }
            });
        });
    </script>
    <h1 id="title">テスト</h1>
    <div id="jsontext"></div>
</html>

実行

$ mix phx.server

データ入力例

http://localhost:4000/usersにアクセスして「New Usre」クリック
image.png

入力後「Seve User」をクリック
image.png

これを繰り返す

APIの動作検証

http://localhost:4000/api/usersにアクセス

image.png

表示例
{"data":[{"id":1,"name":"テスト"},{"id":2,"name":"ほげほげ"},{"id":3,"name":"abcde"}]}

jQuery + getJSONの検証

http://localhost:4000/html/test.htmlにアクセス
image.png

jQuery + getJSONでデータ取得できました

ソース(github)

4
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?