0

这是两个电话——

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 调用的顺序,它将继续执行最后一个函数的回调方法。我希望两者都被执行。

4

1 回答 1

0

您可以使用承诺,也可以只跟踪第二个 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);
        },
    });
}
于 2013-10-30T06:08:19.077 回答