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.
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.
var oldComplete = ajaxOpts.complete; ajaxQueue.queue(function(next) { ajaxOpts.complete = function() { if (oldComplete) oldComplete.apply(this, arguments); next(); }; $.ajax(ajaxOpts); });
};
})(jQuery);
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3