每天一剂Rails良药之RJS
本来题目应该为Update Multiple Page Elements With One Ajax Request,但蛙眼的博客标题字数有限,遂更名为RJS,因为这次主要了解的就是Rails的RJS。让我们看看一个RJS的例子,通过一次Ajax请求灵活的更新页面中的多个元素。
1,新建Rails项目和一个rhtml
如app/views/ajax_fun/index.rhtml:
<html> <head> <%= javascript_include_tag :defaults %> </head> <body> <h2 id="header">AjaxFun</h2> <div> This page was initially loaded at <%= Time.now %> </div> <div> This page was updated at <span id="time_updated"><%= Time.now%></span> </div> <ul id="the_list"> <li>Initially, the first item</li> <li>Another item</li> <li id="item_to_remove">This one will be removed.</li> </ul> <div id="initially_hidden" style="display: none;"> This text starts out hidden. </div> <%= link_to_remote "Ajax Magic", :url => {:action => "change"} %><br/> </body></html>
该页面作为Ajax调用的基本页面,我们用javascript_include_tag引入了Rails自带的JavaScript
注意link_to_remote这个helper方法,它的:url表明我们将用Prototype的Ajax.Request(...)方法调用服务器端的change方法。
2,创建一个controller
如app/controllers/ajax_fun_controller.rb:
class AjaxFunController < ApplicationControllerdef change @rails_version = Rails::VERSION::STRINGendend
3,创建一个RJS模板
因为我们对controller的change方法做RJS,所以我们的RJS模板为app/views/ajax_fun/change.rjs:
page['time_updated'].replace_html Time.nowpage[:time_updated].visual_effect :shakepage.insert_html :top, 'the_list', '<li>King of the Hill</li>'page.visual_effect :highlight, 'the_list'page.show 'initially_hidden'page.delay(3) dopage.alert "Rails Version: " + @rails_versionendpage.remove 'item_to_remove'
4,看看效果
打开浏览器访问http://localhost:3000/ajax_fun,点击Ajax Magic链接即可。
我们的change.rjs更新了time_updated的时间,并有一个shake的effect,然后在the_list的顶端插入一行,并highlight它,然后我们显示了initially_hidden这个隐藏div,然后我们在page load成功3秒后alert我们的Rails的版本,最后删除item_to_remove这行。
页:
[1]