jquery - 将多个 ajax 调用捆绑到 jQuery.when() 中时如何处理错误?

标签 jquery ajax

我想等待多个 AJAX 调用,而不需要将回调嵌套在另一个调用中。

来自this文档,我知道可以使用 jQuery.when()

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the 
        page1 and page2 ajax requests, respectively */
   var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
   if ( /Whip It/.test(jqXHR.responseText) ) {
      alert("First page has 'Whip It' somewhere.");
   }
});

但是,从提供的示例来看,我不明白如何处理错误。在正常的 jquery.ajax 调用中,我在选项中提供 error 回调。

理想情况下,我希望在至少一个 ajax 调用导致错误时调用提供的错误回调。

最佳答案

正确的做法是将 then 链接到 when,而不是 done

例如:

$.when(
   $.ajax("/page1.php", {
    error: function(jqXHR, textStatus, errorThrown){
      // handle the error for this specific call
    },
    success: function(data, textStatus, jqXHR){
      // handle the success for this specific call
    }
   }), 
   $.ajax("/page2.php"), {
    error: function(jqXHR, textStatus, errorThrown){
      // handle the error for this specific call
    },
    success: function(data, textStatus, jqXHR){
      // handle the success for this specific call
    }
   }).then(
   function(){
     // all calls succeeded
   },
   function(){
     // at least one of the calls failed
   }
});

关于jquery - 将多个 ajax 调用捆绑到 jQuery.when() 中时如何处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9580018/

相关文章:

javascript - 服务器端数据表返回额外页面

jquery - ASP.Net MVC 3.0 onclick 打印 View ?

javascript - 如何在ajax响应中隐藏onclick按钮?

javascript - $.post() 调用的返回值

jquery - 将 AJAX 转换为 jQuery

php - 使用 jQuery/Ajax 和 PHP 显示当前进度

php - SQL查询: Data transfer from one database to another database

javascript - 如何在 CKEditor textareas 上触发模糊事件?

jquery - 有哪些选项可以让文本/列表项出现在列中?

javascript - 如何从异步调用返回响应?