深蓝之网络

探讨网站建设,主机,域名,VPS,服务器

« Burst.Net VPS 重装,更换操作系统VPS搭建邮件服务器初尝试 »

Ajax异步请求队列解决方案

使用Ajax请求一系列数据时,会因为异步请求无法判断返回值是那次请次的,而导致错误。
往往只能使用同步请求,而Ajax同步请求往往会锁定浏览器,甚至锁死。

解决方案是用异步请求队列,方案不是原创的,出自《JavaScript设计模式》一书。
发出来备忘,供大家参考。

JavaScript Code
  1. var QueuedHandler = function(){   
  2.     this.queue = []; // 请求队列   
  3.     this.requestInProgress = false// 判断当前是否己有别的请求   
  4.     this.retryDelay = 5; // 设置每次重新请求的时间,单位为秒   
  5. };   
  6. QueuedHandler.prototype = {   
  7.     request:function(method,url,callback,postVars,override){   
  8.         // 如果没有设置为覆盖模式,而且当前已经有别的请求   
  9.         if(this.requestInProgress && !override){   
  10.             this.queue.push({   
  11.                 method:method,   
  12.                 url:url,   
  13.                 callback:callback,   
  14.                 postVars:postVars   
  15.             });   
  16.         }else{   
  17.             this.requestInProgress = true;   
  18.             var xhr = this.createXhrObject();   
  19.             var that = this;   
  20.   
  21.             xhr.onreadystatechange = function(){   
  22.                 if(xhr.readyState !== 4) return;   
  23.                 if(xhr.status === 200){   
  24.                     callback.success(xhr.responseText,xhr.responseXML);   
  25.                     // 判断请求队列是否为空,如果不为空继续下一个请求   
  26.                     that.advanceQueue();   
  27.                 }else{   
  28.                     callback.failure(xhr.status);   
  29.                     // 每过一定时间重新请求   
  30.                     setTimeout(function(){   
  31.                         that.request(method,url,callback,postVars);   
  32.                     },that.retryDelay * 1000);   
  33.                 }   
  34.             };   
  35.   
  36.             xhr.open(method,url,true);   
  37.             if(method!=='POST')postVars = null;   
  38.             xhr.send(postVars);   
  39.         }   
  40.     },   
  41.     createXhrObject:function(){   
  42.         var methods = [   
  43.             function(){return new XMLHttpRequest();},   
  44.             function(){return new ActiveXObject('Msxml2.XMLHTTP');},   
  45.             function(){return new ActiveXObject('Microsoft.XMLHTTP');},   
  46.         ];   
  47.         for(var i=0,len=methods.length;i<len;i++){   
  48.             try{   
  49.              methods[i]();   
  50.             }catch(e){   
  51.                 continue;   
  52.             }   
  53.             //    
  54.             this.createXhrObject = methods[i]; //    
  55.             return methods[i]();   
  56.         }   
  57.   
  58.         throw new Error('SimpleHandler: Could not create an XHR object.');   
  59.     },   
  60.   
  61.     advanceQueue:function(){   
  62.         if(this.queue.length === 0){   
  63.             this.requestInProgress = false;   
  64.             return;   
  65.         }   
  66.         var req = this.queue.shift();   
  67.         this.request(req.method,req.url,req.callback,req.postVars,true);   
  68.     }   
  69. };  

调用方法:

JavaScript Code
  1. var myHandler = new QueuedHandler();   
  2. var callback = {   
  3.     success:function(reponseText){alert(reponseText);},   
  4.     failure:function(statusCode){alert(statusCode);}   
  5. };   
  6.   
  7.     for (var i = 0; i < 5; i++) {
            t_url = "test.ashx?id="+i;
            myHandler.request("Get", t_url, callback);
        }

 

其中还能加入更多功能,比如从 QueuedHandler里反馈出来,正在处理第几个ajax请求;是否已经完成队列;强制停止ajax请求队列等等。


除非注明,文章均为深蓝网络原创,转载请注明出处,谢谢。
本文地址:http://www.dieep.com/Category/program/47.html

相关文章:

最新评论:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新评论及回复

最近发表

Copyright www.dieep.com. All Rights Reserved.

Powered By Z-Blog 1.8 Walle Build 100427