Ruby on Rails で Ajax
Ruby on RailsでAjaxを使ってみた。
RoRにはAjaxを使うためのヘルパーメソッドがあるみたい。
その中の代表例が
1.javascript_include_tag
<%= javascript_include_tag "prototype" %>によりprototype.jsライブラリをインポートします。つまり、
<script src="/javascripts/prototype.js" type="text/javascript"></script>こんな感じになります。
2.link_to_remote
link_to_remote(name, options = {}, html_options = {})
link_toメソッドをAjax風に仕立てたものみたいで、
nameパラメータが表示される文字列
optionsパラメータがDOM のエレメントの id 属性。ここで指定されるid属性の中身がアクションの結果により置き換わる
html_optionsパラメータがアクションURL
ということで、
<%= link_to_remote( "click here",と書けば、ajaxtest_say_whenアクションによって<div id="time_div></div>で囲まれた中身が置き換わります。
:update => "time_div",
:url =>{ :action => :ajaxtest_say_when }) %>
ということで、以前作ったBlogコントローラに
class BlogController < ApplicationController
def index
end
def ajaxtest_say_when
render_text "<p>current time is " + DateTime.now.to_s + " from ajaxtest_say_when</p>"
end
end
と書いて、Viewのindex.rhtmlに
<html>
<head>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<div id="time_div">
current time is
<%= link_to_remote( "click here",
:update => "time_div",
:url =>{ :action => :ajaxtest_say_when }) %>
</div>
</body>
</html>
と書けばできあがる。
まぁ、簡単。