复制代码 代码如下:
;(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进行在线运行,修改等。最后有什么问题,欢迎提出交流 :)
