Home > Article > Web Front-end > How to Sequence AJAX Requests Iteratively
In various scenarios, developers may encounter the need to iterate through a collection, initiating an AJAX request for each element. The objective is to allow each request to complete before proceeding to the next element, steering clear of overwhelming the server with concurrent requests and potential issues. Moreover, avoiding the use of synchronous AJAX calls ensures that the browser remains responsive.
While a common solution involves creating an iterator context that advances upon each successful callback, many seek a more streamlined approach. Here are a few effective design patterns:
The jQuery 1.5 version of the solution utilizes the $.Deferred, $.queue(), and $.ajax() methods. It also provides a promise that resolves upon request completion.
<code class="javascript">$.ajaxQueue = function(ajaxOpts) { 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; };</code>
For earlier versions of jQuery (1.4 specifically), leveraging the animation queue on an empty object provides a means to create a custom "queue" for AJAX requests.
<code class="javascript">(function($) { var ajaxQueue = $({}); $.ajaxQueue = function(ajaxOpts) { var oldComplete = ajaxOpts.complete; ajaxQueue.queue(function(next) { ajaxOpts.complete = function() { if (oldComplete) oldComplete.apply(this, arguments); next(); }; $.ajax(ajaxOpts); }); }; })(jQuery);</code>
Consider the following HTML structure:
<code class="html"><ul id="items"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <ul id="output"></ul></code>
Using the $.ajaxQueue() plugin, you can copy the HTML of the items in #items to #output:
<code class="javascript">$("#items li").each(function(idx) { $.ajaxQueue({ url: '/echo/html/', data: {html : "["+idx+"] "+$(this).html()}, type: 'POST', success: function(data) { $("#output").append($("<li>", { html: data })); } }); });</code>
This approach ensures that the copy requests are handled sequentially, preventing any potential issues arising from excessive server load.
The above is the detailed content of How to Sequence AJAX Requests Iteratively. For more information, please follow other related articles on the PHP Chinese website!