1.将async设置为false,最简单的方法,但是如果执行的ajax调用过多,浏览器会卡死。
2.使用$.when().done().then()。简单测试的代码如下
function GetBatchAjax(id) {
var ajax=$.ajax({
type: "POST",
dataType: "json",
data: "id=" + id,
url: '@Url.Action("Search","Index")'
});
return ajax;
}
$('#PromiseGetPeopleInfo').click(function() {
$.when(GetBatchAjax(1)).done(function (oneResult) {
console.log(oneResult);
$.when(GetBatchAjax(2)).done(function (twoResult) {
console.log(twoResult);
}).fail(function() {
});
}).fail(function() {
});
});
3.使用promise
function GetPromise() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("执行完毕");
}, 2500);
});
}
$('#PromiseTest').click(function () {
var myFirstPromise = GetPromise();
myFirstPromise.then(function (successMessage) {
console.log("Yay! " + successMessage);
});
});