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

问题描述 投票:0回答:2

我想等待多个 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 调用导致错误时调用提供的错误回调。

jquery ajax
2个回答
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
投票

使用 $.when 处理多个请求完成错误处理

var request1 = $.ajax({
    url: '...',
    type: 'GET',
    data: {
        // data
    }
});

var request2 = $.ajax({
    url: '...',
    type: 'GET',
    data: {
        // data
    }
});

$.when(request1, request2)
.done(
    function(response1, response2) {

        // success response from both

        var jsonMvtoData = response1[0];
        var resp1statusCode = response1[2].status;

        var jsonTipoOperacion = response2[0];
        var resp2statusCode = response2[2].status;

})
.fail(function(){

    // One or both requests failed

    [request1, request2].forEach(function(req) {
        req.fail(function(jqXHR) {

           // if both request fails, this will execute twice
           // you can do what u want with the json responses
           // for example store all of them in an array
                
            if (jqXHR.responseText) {
                try {
                    // Parsed JSON from failed request
                    var parsedJSON = JSON.parse(jqXHR.responseText);
                  console.error("JSON from failed request:", jqXHR.responseJSON);
                } catch (e) {
                    console.error("Failed to parse JSON:", e);
                }
            }

        });
    });
});

© www.soinside.com 2019 - 2024. All rights reserved.