2012年2月19日日曜日

rails 3.1 でのajax 2

テンプレートを使うバージョン
手順1:ルーティングの追加(routes.rbにコントローラー ajx アクションasyncを追加) get "ajax/async" 手順2: view に:remote => trueを追加(views/ajax/index.html.erb)

number

<%= link_to 'get num' ,{:action => 'async'} , :remote => true %>
手順3:コントローラーに"async"を追加(controllers/ajax_controller.rb)
  def async
    @num = rand(100)
  end
手順4:コントローラーからコールされるjavascript(views/ajax/async.js.erb)アクション名と同じにする #numの例はテンプレートを使わないパターン
$('#num').text(
 "<%= escape_javascript(render :partial => 'async_num') %>"
);
$('#num2').html(
 "from async.js.erb   " +  "<%=  @num %>"
);
手順5:テンプレート(views/ajax/_async_num.html.erb)(_は必要です)
from _async_num.html.erb   <%= @num %>

0 件のコメント:

コメントを投稿