rails3 rails.js和jquery捕获ajax请求的成功和失败

以前,在rails 2.3.8中,我使用了prototype-helpers link_to_remoteform_remote_for (以及其他)。

这些可以选择:update如下:

 link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } 

( 文档中的一个例子)。 这个例子在成功更新带有“cart”类的html元素时,失败后会出现类“错误”。

现在我相信作案手法已经改变,而是我们写道:

 link_to "Add to cart", :url => {:action => "add", :id => product.id}, :remote => true 

并且没有选项设置:update 。 而不是普通的html,我们现在渲染javascript,就像这样(在jquery中):

 $('.cart').replaceWith( 'cart') %>) 

但是你如何处理错误情况呢? 我是否在控制器中处理它,并使用单独的视图?

以某种方式能够模仿我们以前的行为似乎对我有用。 有任何想法吗?

哈! 我发现它在本文中有描述。 在rails.js中,检查以下回调:

  • ajax:loading:在执行AJAX请求之前触发
  • ajax:success:在成功的AJAX请求之后触发
  • ajax:complete:在AJAX请求完成后触发,无论响应的状态如何
  • ajax:失败:在AJAX请求失败后触发,与ajax相反:success

由于javascript应该是不引人注目的,因此HTML中不会进行此耦合。

一个例子(来自同一站点):以下Rails 2.3.8

 <% form_remote_tag :url => { :action => 'run' }, :id => "tool-form", :update => { :success => "response", :failure => "error" }, :loading => "$('#loading').toggle()", :complete => "$('#loading').toggle()" %> 

被翻译成这个:

 <% form_tag url_for(:action => "run"), :id => "tool-form", :remote => true do %> 

在一些javascript(application.js)中,你绑定事件

 jQuery(function($) { // create a convenient toggleLoading function var toggleLoading = function() { $("#loading").toggle() }; $("#tool-form") .bind("ajax:loading", toggleLoading) .bind("ajax:complete", toggleLoading) .bind("ajax:success", function(xhr, data, status) { $("#response").html(status); }); }); 

大! 🙂

[更新日期:29/12/2011]

最近有两个事件被重命名:

  • ajax:beforeSend :替换已故的ajax:loading
  • ajax:error取代了ajax:failure (我猜想更符合jQuery本身)

所以我的例子将成为:

  $("#tool-form") .bind("ajax:beforeSend", toggleLoading) .bind("ajax:complete", toggleLoading) .bind("ajax:success", function(xhr, data, status) { $("#response").html(status); }); 

为了完整性,事件及其预期参数:

  .bind('ajax:beforeSend', function(xhr, settings) {}) .bind('ajax:success', function(xhr, data, status) {}) .bind('ajax:complete', function(xhr, status) {}) .bind('ajax:error', function(xhr, data, status) {}) 

相关的rails 4指南可在以下url找到: http : //guides.rubyonrails.org/working_with_javascript_in_rails.html

它指向以下事件的文档: https : //github.com/rails/jquery-ujs/wiki/ajax ,如ncherro所述

传递给回调的实际值可以从jQuery的ajax方法中推断出来http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

.bind不推荐使用.on支持.on : http : .on

所以现在推荐的方法是:

模板:

 <%= link_to 'Click me!', 'path/to/ajax', remote: true, id: 'button', method: :get, data: {type: 'text'} %> 

CoffeScript:

 $(document).ready -> $("#button").on("ajax:success", (e, data, status, xhr) -> alert xhr.responseText ).on "ajax:error", (e, xhr, status, error) -> alert "error" 

我知道这个问题是3年之久,但它在Google搜索结果中显得很高,并且上面列出的一些事件不再使用了。

请参阅此处获取最新列表 – https://github.com/rails/jquery-ujs/wiki/ajax