默认情况下,Jquery 在同步模式下工作。
检查 $.ajax 设置的 async:false 值。
否则,您可以在最新的 jQuery 中使用 $.when() 的好处。
// Using the $.when() method, we can create an object that behaves similarly
// to Deferred objects, but for COMBINATIONS of Deferred objects.
//
// The $.when() method creates a Deferred object that is resolved or rejected
// when all the Deferred objects passed into it are resolved or rejected.
var getPromise = function(name) {
var dfd = $.Deferred();
var num = Math.floor(Math.random() * 1000);
setTimeout(function() { dfd.resolve(name + ": " + num); }, num);
return dfd.promise();
};
var list = $("<ul/>").appendTo($("#target").empty());
var printLine = function(str) {
$("<li class=well/>").html(str).appendTo(list);
};
// Each of these Promises will individually print when resolved.
var promiseA = getPromise("A").done(printLine);
var promiseB = getPromise("B").done(printLine);
var promiseC = getPromise("C").done(printLine);
// And this code will execute once all Promises have resolved.
$.when(promiseA, promiseB, promiseC).then(function(numA, numB, numC) {
printLine(numA + ", " + numB + ", " + numC);
});