轨道3:如何使一个Ajax调用? [英] Rails 3: How to make an Ajax call?
问题描述
我想有一个链接(有没有更好的选择吗?)我的网页上点击时,这将使一个Ajax请求。 (我想在我的数据库更新字段中的链接被点击时。)
I would like to have a link (is there a better option?) on my page which will make an Ajax request when clicked. (I would like to update a field in my database when the link is clicked.)
什么是实现这一目标的最简单的方法是什么?
What is the simplest way to achieve this ?
您可以参考我的一些教程?
Could you refer me to some tutorials ?
推荐答案
真的很简单。在你看来,有一个链接/按钮,如下所示。重要的一点是:远程=>真正的
Really simple. In your view, have a link/button like so. Important bit being :remote => true
<%= link_to 'Update Thingy', update_thingy_path, :confirm => 'You sure you wanna update?', :remote => true %>
或
<%= button_to('Update Thingy', {:action => 'update_thingy', :thingyid => 314}, :method => :get, :remote => true) %>
显然,你必须得到update_thingy_path解决一些动作是正常的。当你渲染你将要呈现的一些* .js.erb,而不是* .html.erb所不同的是。在这种update_thingy.js.erb,你只要把任何的JavaScript要在客户端上运行。你可能会想通知的更新发生,例如(在jQuery的)用户:
Obviously, you have to get update_thingy_path to resolve to some action as normal. The difference is when you render you are going to be rendering some *.js.erb instead of *.html.erb. In that update_thingy.js.erb, you just put whatever javascript you want to run in the client. You might wanna notify the user that the update happened for example (in jQuery):
$('#notice').html("Thingy was update.")
或者,如果任何的JavaScript你回来真的很简单,在控制器,你可以这样做以下,而不必整体js.erb为一个班轮。
Or if whatever javascript you're returning is really simple, in the controller you can do something like the following instead of having a whole js.erb for a one-liner.
render :js => "alert('Blah')"
这篇关于轨道3:如何使一个Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!