常常 一系列 的 Ajax 请求之间 要求 有一定的次序要求,依赖关系,以及为了防止突发网络故障需要一定的自动重练功能。
例如:
1.b请求必须要在a请求返回后执行。
2.b请求要求必须a操作成功后再执行。
3.a 请求失败了就重练3次,最后仍然失败,则b请求取消
那么传统在每个callback中分别判断写得很死就很那重用了,实现一个队列来集中管理吧。
<script>
function AjaxQueue(){
this.restore();
};
//重用对象,清除队列
AjaxQueue.prototype.restore = function(){
//函数队列
this._queue=[];
//队列当前函数重试次数
this._retry=0;
//是否当前失败
this._stopped=false;
},
//没有停止就添加执行
AjaxQueue.prototype.addToQueue = function(func){
if(this._stopped) return;
this._queue.push(func);
if(this._queue.length==1)
this._start();
};
AjaxQueue.prototype.retry = function(maxRetry){
//失败
if(this._retry<maxRetry){
this._retry++;
this._queue[0]();
}
else {
//超过最大重试次数,清空队列,其他等待处理的ajax 作废(依赖于上一个操作)
this.stop();
}
};
AjaxQueue.prototype.next = function(){
//当前处理函数弹出,处理下一个
this._queue.shift();
this._start();
},
//
AjaxQueue.prototype._start = function(){
if(this._queue.length==0) {
//全部处理完了
return;
}
this._retry=0;
this._queue[0]();
};
AjaxQueue.prototype.stop = function(){
this._queue=[];
this._stopped=true;
};
var mger = new AjaxQueue();
var maxRetry=3;
(function yy(){
var z=prompt("input");
mger.addToQueue(function (){
/*
Ajax.request({
success:function(){
//成功了,通知队列执行下一个
mger.next();
},
err:function(){
//失败了,通知队列重试当前函数
mger.retry(maxRetry);
}
});
*/
alert(z);
//通知队列执行下一个
//mger.next();
//重试,最终导致取消
mger.retry(maxRetry);
});
mger.addToQueue(function (){
alert(z+"_1");
mger.next();
});
})();
</script>
本文介绍了一个用于管理Ajax请求的队列系统,确保请求按顺序执行并具备重试机制。通过自定义的AjaxQueue类,实现了请求间的依赖关系,并在失败时进行重试,最后取消未完成的操作。
78

被折叠的 条评论
为什么被折叠?



