Heim  >  Artikel  >  Web-Frontend  >  jquer之ajaxQueue简单实现代码_jquery

jquer之ajaxQueue简单实现代码_jquery

WBOY
WBOYOriginal
2016-05-16 18:02:031101Durchsuche

没什么复杂的东西,就是用个array对象来做队列,维护ajax请求的顺序。下面给出代码:

复制代码 代码如下:

;(function($) {
$.ajaxQueue = {
// 管理ajax请求的队列
requests: new Array(),
// 把待发送的ajax请求加入队列
offer: function(options) {
var _self = this,
// 对complete,beforeSend方法进行“劫持”,加入队列处理方法poll
xhrOptions = $.extend({}, options, {
// 如果请求完成,发送下一个请求
complete: function(jqXHR, textStatus) {
if(options.complete)
options.complete.call(this, jqXHR, textStatus);
_self.poll();
},
// 如果请求被取消,继续发送下一个请求
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);
}
},
// 用FIFO方式发送ajax请求
poll: function() {
if(this.isEmpty()) {
return null;
}
var processedRequest = this.requests.shift();
var nextRequest = this.peek();
if(nextRequest != null) {
$.ajax(nextRequest);
}
return processedRequest;
},
// 返回队列头部的ajax请求
peek: function() {
if(this.isEmpty()) {
return null;
}
var nextRequest = this.requests[0];
return nextRequest;
},
// 判断队列是否为空
isEmpty: function() {
return this.requests.length == 0;
}
}
})(jQuery);

使用的话就是$.ajaxQueue.offer(settings),settings的配置和jQuery文档的一致。
如果您感兴趣,可以点击我的jsFiddle share进行在线运行,修改等。最后有什么问题,欢迎提出交流 :)

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn