并行jquery ajax调用仅触发最后一次调用的回调方法

时间:2013-10-30 05:54:22

标签: jquery ajax

这是两个电话 -

var url = '/Home/ListData?ipaddress=' + ipaddress;
processAjaxRequest(url , 'Post', 'fetchDataComplete', DataModel);

processAjaxRequest('/Home/ListException', 'Post', 'fetchExceptionComplete',DataModel);

function processAjaxRequest(urlToProcess, httpMethod, successCallback, postData) {

    $.ajax({
        url: urlToProcess,
        type: httpMethod,
        data: dataToPost,
        success: function (data, status) {
            var fn = window[successCallback];
            fn(data);
        },
        error: function (xhr, desc, err) {
            processAjaxError(xhr, desc, err);
        },
    });
}

function fetchDataComplete(data) {

    //some stuff

}

function fetchExceptionComplete(data) {

    //some stuff

}

如果我改变了ajax调用的顺序,它将继续执行最后一个函数的回调方法。我希望两者都被执行。

1 个答案:

答案 0 :(得分:0)

您可以使用promises,也可以跟踪第二个ajax调用何时完成,如下所示:

var url = '/Home/ListData?ipaddress=' + ipaddress;
// set state for how many ajax calls we're waiting for
var callsRemaining = 2;
processAjaxRequest(url , 'Post', 'fetchDataComplete', DataModel);
processAjaxRequest('/Home/ListException', 'Post', 'fetchExceptionComplete',DataModel);

function processAjaxRequest(urlToProcess, httpMethod, successCallback, postData) {
    $.ajax({
        url: urlToProcess,
        type: httpMethod,
        data: dataToPost,
        success: function (data, status) {
            --callsRemaining;
            if (callsRemaining <= 0) {
                 var fn = window[successCallback];
                 fn(data);
            } else {
                 // perhaps store the data from the first ajax call that completed
            }
        },
        error: function (xhr, desc, err) {
            processAjaxError(xhr, desc, err);
        },
    });
}