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