jQuery 如何使用 remote_function 使用 Rails 3 进行 Ajax 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3332474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Ajax calls with Rails 3 using remote_function?
提问by Hitesh Manchanda
I am trying to make an onchange call on a select box.For my application i am using jquery.js and rails.js as mentioned to make use of UJS. But still the code that is generated is for Prototype and not for jquery ajax calls. My code looks like the following:
我正在尝试在选择框上进行 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()") %>
The code that is generated by this is:
由此生成的代码是:
new Ajax.Request('/posts/filter_posts?filter=category', {asynchronous:true, evalScripts:true,
parameters:'category_id=' + $('#category').val() + '&authenticity_token=' +
encodeURIComponent('CCyYj1wqXtddK6pUV6bAxw0CqZ4lbBxDGQHp13Y/jMY=')})
回答by Confusion
As Sergei said: There is no remote_function in rails 3.
正如 Sergei 所说:rails 3 中没有 remote_function。
The solution is to unobtrusively add the onchange handler using something like:
解决方案是使用以下内容不显眼地添加 onchange 处理程序:
$(function($) {
$("#selector_for_element").change(function() {
$.ajax({url: '<%= url_for :action => 'action_name', :id => @model.id %>',
data: 'selected=' + this.value,
dataType: 'script'})
});
});
This will call the action_name
method in the current controller, passing the result of selected=...
as a parameter. Now you can return a piece of javascript, for instance using something like:
这将调用action_name
当前控制器中的方法,并将结果selected=...
作为参数传递。现在您可以返回一段 javascript,例如使用以下内容:
calculated = calculate_some_value_using(params[:selected])
render(:update) {|page|
page << "$('#selector_for_field_to_update).html(#{calculated})"
}
in the controller. The string you append to ''page'' should be valid javascript and will be executed automatically if you use $.ajax.
在控制器中。您附加到''page'' 的字符串应该是有效的javascript,如果您使用$.ajax,它将自动执行。
EDIT: FYI, we recently added a select change helper to jquery-ujs, so you can do this unobtrusive way using the built-in jquery-ujs adapter now:
编辑:仅供参考,我们最近向 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") } %>
Though to be fair, adding a select change event really isn't ever going to be "unobtrusive" as there is no graceful fallback for users with javascript disabled unless your form doesn't depend on the result of the AJAX request.
虽然公平地说,添加一个选择更改事件真的永远不会“不引人注目”,因为禁用 javascript 的用户没有优雅的回退,除非您的表单不依赖于 AJAX 请求的结果。
回答by Sergei Smychkovich
There is no remote_function in rails 3. If you're using jQuery, you can do something like this:
rails 3 中没有 remote_function。如果您使用的是 jQuery,则可以执行以下操作:
$.ajax({
type: 'POST',
url: 'http://your_url/blah',
data: 'param1=value1¶ms2=value2',
success: function(data){eval(data);}
});
回答by Pravin
Following is the simple jQuery snippet from my haml view
以下是我的 haml 视图中的简单 jQuery 片段
:javascript
$("#select_box_id").change(function() {
$.post('#{target_url}?param_one='+$(this).val());
});
Hope this helps. Thanks..
希望这可以帮助。谢谢..
回答by QuarkleMotion
If you face the issue that I had of upgrading a large rails app to rails 3 that made heavy use of remote_function, you can achieve limited backwards compatibility by adding a application_helper method that generates jQuery code in the format suggested by other answers here. I was able to use this code as is, though had to update one piece of calling code to use the new :success script option instead of the :update hash option that is not supported here. This can buy you some time to eventually refactor all remote_function calls to use unobtrusive jquery-ujs event callbacks:
如果您面临将大型 rails 应用程序升级到大量使用 remote_function 的 rails 3 的问题,您可以通过添加 application_helper 方法来实现有限的向后兼容性,该方法以此处其他答案建议的格式生成 jQuery 代码。我能够按原样使用此代码,但必须更新一段调用代码以使用新的 :success 脚本选项,而不是此处不支持的 :update hash 选项。这可以让您有时间最终重构所有 remote_function 调用以使用不显眼的 jquery-ujs 事件回调:
def remote_function(options)
("$.ajax({url: '#{ url_for(options[:url]) }', type: '#{ options[:method] || 'GET' }', " +
"data: #{ options[:with] ? options[:with] + '&' : '' } + " +
"'authenticity_token=' + encodeURIComponent('#{ form_authenticity_token }')" +
(options[:data_type] ? ", dataType: '" + options[:data_type] + "'" : "") +
(options[:success] ? ", success: function(response) {" + options[:success] + "}" : "") +
(options[:before] ? ", beforeSend: function(data) {" + options[:before] + "}" : "") + "});").html_safe
end
回答by vidur punj
Ajax Call to controllers-action with parameters:
Ajax 调用带有参数的控制器动作:
function combined_search() {
var countries = $('#countries').val();
var albums = $('#albums').val();
var artists = $('#artists').val();
$.ajax({
url:"<%=url_for :controller => 'music_on_demand',:action => 'combined_search' %>",
data:'country=' + encodeURIComponent(countries) + '&albums=' + encodeURIComponent(albums) + '&artists=' + encodeURIComponent(artists),
cache:false,
success:function (data) {
}
})
}