2011年11月6日日曜日

rails3.1 でのAjax

ポイントは:remote => true とアクション名と同じ名前のjavascriptです。

bookのタイトルをindex.htmlで表示させて、その本に関連するリンクをクリックした場合Ajaxでコンテンツを表示する場合は以下のようになります。
今までajaxの必要性が無かったので、殆ど調べてい無かったので、方法をメモとして残しておきます。

手順1:
/app/views/books/index.html.erb
以下を追加
<%= link_to('content' , {:action => 'content',:id => book.id}  ,:id => "content_id" , :remote => true) %>

手順2:
/config/routes.rb
以下を追加

get "books/content"

手順3:
/app/controllers/books_controller.rb
以下を追加
 def content
  @book = Book.find(params["id"])
  end

手順4:
/app/views/books/content.js.erb を作成して内容を以下のようにする
$(function(){
  $("#content_id")
    .live("ajax:beforeSend", function(){ 
    //alert("loading"); 
    }) 
    .live("ajax:success", function(){
    //alert("success"); 
    $('#content').empty();
$('#content').append('<%= @book.content %>');
    }) 
    .live("ajax:error", function(){
    //alert("error");
    }) 
    .live("ajax:complete", function(){ 
    //alert("complete"); 
    });
});

流れとしては手順1でcontentアクションに対して非同期通信設定を行う。クリックイベントでコントローラ内のcontentが実行される。その後content.js.erbに入ってきて、その中でビューの表示の更新をする。





0 件のコメント:

コメントを投稿