In the scenario where you need to iterate through a collection and perform an AJAX request for each element sequentially, maintaining server performance and avoiding browser freeze can be challenging. Here are innovative approaches for solving this issue:
jQuery 1.5 :
Utilize the $.ajaxQueue() plugin, which employs the Deferred, queue(), and $.ajax() mechanisms. This plugin manages the creation of an AJAX request queue and provides a promise that resolves upon request completion.
(function($) { // Create an empty object as the AJAX request queue var ajaxQueue = $({}); $.ajaxQueue = function(ajaxOpts) { // Define the deferred object and its promise var dfd = $.Deferred(), promise = dfd.promise(); // Enqueue the AJAX request ajaxQueue.queue(doRequest); // Add an abort method to the promise promise.abort = function(statusText) { // Abort the request if active if (jqXHR) { return jqXHR.abort(statusText); } // Remove the request from the queue var queue = ajaxQueue.queue(), index = $.inArray(doRequest, queue); if (index > -1) { queue.splice(index, 1); } // Reject the deferred dfd.rejectWith(ajaxOpts.context || ajaxOpts, [promise, statusText, ""]); return promise; }; // Define the function to execute the request function doRequest(next) { jqXHR = $.ajax(ajaxOpts) .done(dfd.resolve) .fail(dfd.reject) .then(next, next); } return promise; }; })(jQuery);
jQuery 1.4:
If using jQuery 1.4, you can leverage the animation queue on an empty object to establish a custom "queue" for AJAX requests.
(function($) { // Create an empty object as the AJAX request queue var ajaxQueue = $({}); $.ajaxQueue = function(ajaxOpts) { // Hold the original complete function var oldComplete = ajaxOpts.complete; // Enqueue the AJAX request ajaxQueue.queue(function(next) { // Define a complete callback to proceed with the queue ajaxOpts.complete = function() { // Execute the original complete function, if present if (oldComplete) oldComplete.apply(this, arguments); next(); // Proceed to the next request }; // Execute the request $.ajax(ajaxOpts); }); }; })(jQuery);
Example Usage:
With these techniques, you can sequence AJAX requests for each item in a collection, ensuring server performance while avoiding browser lock-ups.
The above is the detailed content of How to Sequentially Execute AJAX Requests in JQuery for Optimal Performance?. For more information, please follow other related articles on the PHP Chinese website!