现在的位置: 首页 > 综合 > 正文

自动排队的异步Ajax请求

2013年11月10日 ⁄ 综合 ⁄ 共 2150字 ⁄ 字号 评论关闭

自动排队的异步Ajax请求

这两天正在为Ajax同步请求会临时锁住浏览器的问题而烦恼,没想到今天在看《JavaScript设计模式》发现了解决方法,里面有一段可以自动排队的异步Ajax请求的代码范例。看到这段代码真有种众里寻她千百度,蓦然回首,那人却在灯火阑珊处的感觉,哈哈。现在把它整理下,用着慢慢用。

var QueuedHandler = function(){
	this.queue = []; // 请求队列
	this.requestInProgress = false; // 判断当前是否己有别的请求
	this.retryDelay = 5; // 设置每次重新请求的时间,单位为秒
};
QueuedHandler.prototype = {
	request:function(method,url,callback,postVars,override){
        // 如果没有设置为覆盖模式,而且当前已经有别的请求
        if(this.requestInProgress && !override){
            this.queue.push({
                method:method,
                url:url,
                callback:callback,
                postVars:postVars
            });
		}else{
            this.requestInProgress = true;
            var xhr = this.createXhrObject();
            var that = this;

            xhr.onreadystatechange = function(){
                if(xhr.readyState !== 4) return;
                if(xhr.status === 200){
                    callback.success(xhr.responseText,xhr.responseXML);
                    // 判断请求队列是否为空,如果不为空继续下一个请求
                    that.advanceQueue();
                }else{
                    callback.failure(xhr.status);
                    // 每过一定时间重新请求
                    setTimeout(function(){
                        that.request(method,url,callback,postVars);
                    },that.retryDelay * 1000);
                }
            };

            xhr.open(method,url,true);
            if(method!=='POST')postVars = null;
            xhr.send(postVars);
        }
	},
	createXhrObject:function(){
        var methods = [
            function(){return new XMLHttpRequest();},
            function(){return new ActiveXObject('Msxml2.XMLHTTP');},
            function(){return new ActiveXObject('Microsoft.XMLHTTP');},
        ];
        for(var i=0,len=methods.length;i<len;i++){
            try{
           	 methods[i]();
            }catch(e){
            	continue;
            }
            // 如果执行到这里就表明 methods[i] 是可用的
            this.createXhrObject = methods[i]; // 记住这个方法,下次使用不用再判断
            return methods[i]();
		}

		throw new Error('SimpleHandler: Could not create an XHR object.');
	},

	advanceQueue:function(){
        if(this.queue.length === 0){
            this.requestInProgress = false;
            return;
        }
        var req = this.queue.shift();
        this.request(req.method,req.url,req.callback,req.postVars,true);
	}
};

用以下方法调用,你会发现,除第一个请求外,其它的请求都会在上一个请求完全完成后才执行的。

var myHandler = new QueuedHandler();
var callback = {
	success:function(reponseText){console.log('Success');},
	failure:function(statusCode){console.log('Failure');}
};
myHandler.request('GET','feedProxy.php?feed=http://julabs.me/blog/feed/rss/',callback);
myHandler.request('GET','feedProxy.php?feed=http://julabs.me/blog/feed/rss/',callback);
myHandler.request('GET','feedProxy.php?feed=http://julabs.me/blog/feed/rss/',callback);
myHandler.request('GET','feedProxy.php?feed=http://julabs.me/blog/feed/rss/',callback);
【上篇】
【下篇】

抱歉!评论已关闭.