我正在尝试在选择框上进行onchange调用。对于我的应用程序,我正在使用如上所述的jquery.js和rails.js来利用UJS。但是仍然生成的代码是针对Prototype的,而不是针对jquery ajax调用的。我的代码如下所示:
<%= select_tag :category,
options_for_select(
Category.find(:all,:select=>"name,id").collect{|c| [c.name,c.id]}),
:onchange => remote_function(:url => {:controller => "posts",
:action => "filter_post",
:filter =>"category"},
:with=>"'category_id=' + $('#category').val()") %>
由此生成的代码是:
new Ajax.Request('/posts/filter_posts?filter=category', {asynchronous:true, evalScripts:true,
parameters:'category_id=' + $('#category').val() + '&authenticity_token=' +
encodeURIComponent('CCyYj1wqXtddK6pUV6bAxw0CqZ4lbBxDGQHp13Y/jMY=')})
最佳答案
正如Sergei所说:rails 3中没有remote_function。
解决方案是使用类似以下内容毫不干扰地添加onchange处理程序:
$(function($) {
$("#selector_for_element").change(function() {
$.ajax({url: '<%= url_for :action => 'action_name', :id => @model.id %>',
data: 'selected=' + this.value,
dataType: 'script'})
});
});
这将在当前控制器中调用
action_name
方法,将selected=...
的结果作为参数传递。现在,您可以返回一段javascript,例如,使用类似以下内容的代码:calculated = calculate_some_value_using(params[:selected])
render(:update) {|page|
page << "$('#selector_for_field_to_update).html(#{calculated})"
}
在控制器中。附加到“页面”的字符串应为有效的javascript,如果使用$ .ajax,则将自动执行。
编辑:仅供参考,我们最近向jquery-ujs添加了一个选择更改帮助器,因此您现在可以使用内置的jquery-ujs适配器来做到这一点:
<%= select_tag :category_id,
options_for_select(
Category.find(:all,:select=>"name,id").collect{|c| [c.name,c.id]}),
:data => { :remote => true, :url => url_for(:controller => "posts",
:action => "filter_post",
:filter =>"category") } %>
公平地说,添加选择更改事件永远不会“毫不费力”,因为禁用javascript的用户不会有任何后退,除非您的表单不依赖于AJAX请求的结果。
关于jquery - 如何使用remote_function在Rails 3中进行Ajax调用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3332474/