目的
- 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」クリック
これを繰り返す
APIの動作検証
http://localhost:4000/api/users
にアクセス
表示例
{"data":[{"id":1,"name":"テスト"},{"id":2,"name":"ほげほげ"},{"id":3,"name":"abcde"}]}
jQuery + getJSONの検証
http://localhost:4000/html/test.html
にアクセス
jQuery + getJSONでデータ取得できました
ソース(github)