使用jQuery中的延迟对象为多个ajax调用处理不同的成功和失败状态 [英] Handling different success and fail states for multiple ajax call using deferred objects in jQuery

查看:96
本文介绍了使用jQuery中的延迟对象为多个ajax调用处理不同的成功和失败状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$.when为同时查询的所有多个ajax调用返回Deferred对象.

$.when returns a Deferred object for all the multiple ajax calls queried simultaneously.

如果一切成功,则执行.done(),并且如果任何URL失败,则执行.fail().

If everything succeeds .done() executes and if any one of the url fails .fail() executes.

如何处理部分成功状态? (即)如果将5个网址传递给$.when,如果3个成功,则需要处理成功状态,如果2个失败,则需要处理失败状态.

How to handle partial success states? (i.e) if 5 urls are passed to $.when, if 3 succeeds we need to handle success state and it 2 fails we need to handle failure state.

$.when($.getJSON(headerUrl), $.getJSON(tasksUrl), $.getJSON(testingTrackerUrl), $.getJSON(highlightsUrl)))
    .then(function(headerData, tasksData,testingTrackerData,highlightsData) {
        printData(headerData, tasksData,testingTrackerData,highlightsData);
    })
    .fail(function(data, textStatus, jqXHR) {
        console.error('Got error in '+jqXHR);
});

推荐答案

尝试

var request = function (url) {
        return $.getJSON(url)
}
, requests = [
    headerUrl
    , tasksUrl
    , testingTrackerDataUrl
    , highlightsDataUrl
];
// return array of `resolved` , `rejected` jqxhr objects
$.when(
    $.map(requests, function (_request, i) {
         return request(_request)
    })
)
// do stuff with `resolved` , `rejected` jqxhr objects
.always(function (arr) {
    $.each(arr, function (key, value) {
        // `success`
        value.then(function (data, textStatus, jqxhr) {
            console.log(data, textStatus, jqxhr);
            printData(data)
        }
        // `error`
        , function (jqxhr, textStatus, errorThrown) {
            console.log(jqxhr, textStatus, errorThrown)
        })
    })
});

jsfiddle http://jsfiddle.net/guest271314/91Lomwr3/

jsfiddle http://jsfiddle.net/guest271314/91Lomwr3/

这篇关于使用jQuery中的延迟对象为多个ajax调用处理不同的成功和失败状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆