2012-03-06 57 views
2

我想等待多个AJAX调用,而不需要将回调嵌套在另一个中。如何在将多个Ajax调用捆绑到jQuery.when()中时处理错误?

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调用导致错误时调用提供的错误回调函数。

+0

你可以得到结果'A1 [0]'和'A2 [0]'。然后你可以测试''“成功”'或'“错误”'。 – 2012-03-06 08:16:07

+0

你确定吗?我试过了,传递给'done'的函数没有被调用。 – Ovesh 2012-03-07 01:21:34

回答

0

正确的做法是将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 
    } 
}); 
+0

这似乎并没有为我使用jquery-2.0.3 – Victor 2015-12-22 00:15:46