我想等待多个 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/