1.prototype是rails 的内置javascript库。prototype.js文件默认是在public/javascripts目录下
2..rhtml页面导入prototype.js
- <%=javascript_include_tag "prototype"%>
3. link_to_remote使用
在test1.rhtml里发起ajax调用
- <%= link_to_remote("Do the ajax thing",:update => 'mydiv',:url => { :action => :say_hello })%>
- <div id="mydiv"> the text will be chanaged</div>
可以通过查看生成页面的源文件,可以看到这段代码最终生成的为:
js 代码
- <a href="#" onclick="new Ajax.Updater('mydiv', '/ajax_test/say_hello', {asynchronous:true, evalScripts:true}); return false;">Do the ajax thing</a>
- <div id="mydiv"> the text will be chanaged</div>
可以看到要执行ajax_test_controller里的say_hello方法
所以需要定义一个say_hello方法
ruby 代码
- def say_hello
- #不使用任何layout
- render(:layout => false)
- end
定义对应试图say_hello.rhtml
- <em>hello from ajax </em>
运行即可看到效果
Rails AJAX 实现
本文介绍如何在Rails应用中使用prototype.js实现AJAX调用。通过link_to_remote方法创建了一个AJAX链接,点击后会更新页面上的指定元素内容,并展示了如何在控制器中定义相应的方法。

被折叠的 条评论
为什么被折叠?



