Home >Web Front-end >JS Tutorial >jquer's ajaxQueue simple implementation code_jquery

jquer's ajaxQueue simple implementation code_jquery

WBOY
WBOYOriginal
2016-05-16 18:02:031157browse

There is nothing complicated, just use an array object to queue and maintain the order of ajax requests. The code is given below:

Copy code The code is as follows:

;(function($) {
$.ajaxQueue = {
// Manage the queue of ajax requests
requests: new Array(),
// Add the ajax request to be sent to the queue
offer: function(options) {
var _self = this,
// "Hijack" the complete and beforeSend methods, and add the queue processing method poll
xhrOptions = $.extend({}, options, {
// If The request is completed, send the next request
complete: function(jqXHR, textStatus) {
if(options.complete)
options.complete.call(this, jqXHR, textStatus);
_self.poll ();
},
// If the request is canceled, continue to send the next request
beforeSend: function(jqXHR, settings) {
if(options.beforeSend)
var ret = options.beforeSend.call(this, jqXHR, settings);
if(ret === false) {
_self.poll();
return ret;
}
}
});
this.requests.push(xhrOptions);
if(this.requests.length == 1) {
$.ajax(xhrOptions);
}
},
//Send ajax request in FIFO mode
poll: function() {
if(this.isEmpty()) {
return null;
}
var processedRequest = this. requests.shift();
var nextRequest = this.peek();
if(nextRequest != null) {
$.ajax(nextRequest);
}
return processedRequest;
},
// Return the ajax request at the head of the queue
peek: function() {
if(this.isEmpty()) {
return null;
}
var nextRequest = this.requests[0];
return nextRequest;
},
// Determine whether the queue is empty
isEmpty: function() {
return this.requests.length = = 0;
}
}
})(jQuery);

To use it, it is $.ajaxQueue.offer(settings). The configuration of settings is consistent with the jQuery document.
If you are interested, you can click on my jsFiddle share to run it online, modify it, etc. If you have any questions at the end, please feel free to discuss them :)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn