0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのAjax通信で任意のオブジェクトを出力する

Last updated at Posted at 2018-11-24

はじめに

Ajaxとう単語をずっとかっこいいと思っていましたが、一度も使ったことがなかったので、実際に使ってみました。
ここでは、Railsでの実装となります。

Scaffoldを使って簡単に実装していきますので、暖かく見守ってください。

今回作るもの

今回作るものはいたってシンプルで、リンクをクリックすると既存のデータをAjaxで取り出すというもの。

ajax_test.gif

jQueryを導入

layoutファイルがあるので、headの中にscriptタグを書きます。
今回はCDNから引っ張ってきました。

app/views/layouts/application.html.erb

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

とりあえず動くアプリを作成

Scaffoldでユーザーリストが表示されるアプリを作ります。

rails g ajax_test
cd ajax_test
rails g scaffold user name:string
rails db:migrate

データを入れる

db/seeds.rb
(1..10).each do |i|
  User.create(name: "ユーザー#{i}")
end

データを流し込んで、しっかりデータが入っていればOKです!

rails db:seed
rails c
> User.count
=> 10

controller

app/controllers/users_controller.rb
def ajax_test
  @user = User.all
  render json: @user
end

root

config/routes.rb
Rails.application.routes.draw do
  resources :users
  get "ajax_test", to: "users#ajax_test"
end

この時点で
http://localhost:3000/ajax_testにアクセスしてみてください。
localhost_3000_ajax_test.png
すると、こんな感じにjsonデータで返ってきてるのがわかると思います。
今回はこれをviewで良い感じに出力できるようにします。

view

remote: trueをつけることで、Ajax通信してくれるようになります。

app/views/users/index.html.erb
<h1>AjaxTest</h1>
<%= link_to "全てのuserを表示", ajax_test_path, {id: "ajax_test", remote: true} %>

<table id="user"></table>

jsファイルを作る

app/assets/javascripts/ajax_test.js.coffee
$ ->
  $("#ajax_test").click ->
    $.ajax
      url: '/ajax_test'
      type: 'get'  #get,postの指定
      dataType: 'json' #レスポンスのデータタイプ指定
      async: true #非同期通信フラグ
    .done (response) ->
      #処理が成功した時の処理
      $("#user").append("<tr><th>名前</th></tr>")
      for i in [0..response.length]
        $("#user").append("<tr><td>" + response[i].name + "</td></tr>")
    .fail (response) ->
      #処理が失敗した時の処理
      alert 'fail'

処理の流れとしては、

  1. ajax_testというidをクリックすると、イベントが呼び出される 
  2. url: '/ajax_test'で、ajax_testにアクセスするとレスポンスとしてjsonデータが返ってくる
  3. 通信に成功(done)すると、指定したidに要素 + jsonデータを出力
    (失敗したらアラート)

という感じでしょうか。

これでhttp://localhost:3000/usersにアクセスし、リンクをクリックしてみてると、リロードされずに保存された全ユーザーが表示されたかと思います。

まとめ

Ajaxを使うことで、いちいちリロードを待たなくて済むからユーザービリティーが上がるし、すごいなと実感。
(今回の例では逆に使いにくくしてますが)

今後も勉強していきます。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?