When iterating through a collection and making individual Ajax calls for each element, it's essential to control the sequence to prevent server overload and browser freezing. While custom iterators can be employed, there are more elegant solutions available.
In jQuery 1.5 and above, the $.ajaxQueue() plugin leverages $.Deferred, $.queue(), and $.ajax() to manage request sequencing and provide a promise that resolves upon request completion.
<br>(function($) {</p> <p>var ajaxQueue = $({});</p> <p>$.ajaxQueue = function( ajaxOpts ) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); ajaxQueue.queue( doRequest ); promise.abort = function( statusText ) { if ( jqXHR ) { return jqXHR.abort( statusText ); } var queue = ajaxQueue.queue(), index = $.inArray( doRequest, queue ); if ( index > -1 ) { queue.splice( index, 1 ); } dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] ); return promise; }; function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ) .done( dfd.resolve ) .fail( dfd.reject ) .then( next, next ); } return promise;
};
})(jQuery);
For jQuery 1.4, the animation queue can be utilized for creating a custom "queue." You can also create your own $.ajaxQueue() plugin that uses jQuery's 'fx' queue to automatically initiate the first request in the queue if it's not already running.
<br>(function($) {<br> var ajaxQueue = $({});</p> <p>$.ajaxQueue = function(ajaxOpts) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var oldComplete = ajaxOpts.complete; ajaxQueue.queue(function(next) { ajaxOpts.complete = function() { if (oldComplete) oldComplete.apply(this, arguments); next(); }; $.ajax(ajaxOpts); });
};
})(jQuery);
<br>$("#items li").each(function(idx) {<br> $.ajaxQueue({</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">url: '/echo/html/', data: {html : "["+idx+"] "+$(this).html()}, type: 'POST', success: function(data) { $("#output").append($("<li>", { html: data })); }
});
});
This ensures that each Ajax request is executed sequentially, allowing for graceful handling of server load and maintaining browser responsiveness.
The above is the detailed content of How to Sequence Ajax Requests for Optimal Control?. For more information, please follow other related articles on the PHP Chinese website!