I need to be able to control the order of items being processed in the $(document).ready
event.
ready
event. They all start an async call to the server (AJAX). Only after they are all done, I need to do some extra work.
What would be开发者_如何学C the elegant solution for this?
Asynchronous requests fire in order, but will return in whatever order they complete in first. So there is not a sure fire way to force them to end at the same time, however, you can build rules to only run code after certain groups have returned.
For instance, define a callback function with a set of rules, and pass it to each success
callback for all of your ajax requests.
var completedObject = {};
function groupSuccessCallback() {
// Test for any combination of requirements
if ( completedObject.ajax1 && completedObject.ajax2 ) {
... // Do something that only requires 1 and 2
}
if ( completedObject.ajax1 && completedObject.ajax2 && completedObject.ajax3) {
... // Do something that requires all 3 being done
// your data is available at completedObject.ajax#
}
// Or test for _all_ entries for a dynamic count
var allComplete = true;
for(var i in completedObject) {
if ( completedObject.hasOwnProperty(i) && !completedObject[i] ) {
allComplete = false;
}
}
// Do whatchya need.
if (allComplete) {
alert("bb-b-bb-b-b-b-bbb... that's all folks!");
}
}
Then set the flags inside of your success functions:
// Ajax1
completedObject['anything'] = false; // instantiate a dynamic entry in the object or use an array if you can't use names.
$.ajax({
...,
...,
success: function(data) {
completedObject['anything'] = data || true;
groupSuccessCallback();
}
});
John Resig on function evaluation order in $(document).ready:
Every time a new function is added to the queue, it's just being added to an array - then being popped back off again when executed. Let me know if this does not happen for you.
$.readyList - only in pre 1.4 versions
jQuery exposed a property called $.readyList
, which is an array to allow function orded manipulation, however $.readyList in no longer publicly exposed in jQuery 1.4.0
Hackerish way
you can try $(window).load(function () {});
, it should execute after the whole window has loaded (not when document is ready, as it is with $(document).ready()
Depending on the rest of the page, doing that "extra work" in an $.ajaxStop handler might be a more elegant option.
However, it wouldn't be appropriate if the user is able and/or likely to trigger subsequent $.ajax() calls while those initial calls are in progress. In that case, their manually triggered calls may prolong the $.ajaxStop event further than intended.
Create variable that holds a value of 0. On the success function of each Ajax call increment that value by 1 and check if that value equals your total number of calls if it does execute your completeion function.
精彩评论