对象变量中的Javascript HTTP Request Queue - 初始化不起作用

时间:2009-11-20 10:23:15

标签: javascript object variables queue xmlhttprequest

我从这个博客获得了以下Request Queue实现:

http://dsgdev.wordpress.com/2006/10/28/building-a-javascript-http-request-queue/

并希望用对象变量包装它。不幸的是,里面的变量初始化不起作用。

希望有人可以帮我解决这个问题。提前致谢

var requestQueue = {
    inCall          : false,            // VARIABLE TO TRACK IF WE ARE CURRENTLY IN A CALL
    callToArray     : new Array(),      // QUEUE FOR CALLS
    returnToArray   : new Array(),      // QUEUE FOR FUNCTION TO EXECUTE WHEN CALL COMPLETE
    reqMethodArray  : new Array(),      // QUEUE FOR REQUEST METHOD

    createRequestObject : function(){
      var reqObj;
      var browser = navigator.appName;
      if(browser == "Microsoft Internet Explorer"){
        reqObj = new ActiveXObject("Microsoft.XMLHTTP");
        isIE = true;
      }else{
        reqObj = new XMLHttpRequest();
      }
      return reqObj;
    },

    sendCall : function(whereTo, returnTo, reqMethod){
      // GET THE NEXT ARRAY ITEM AND REMOVE FROM THE ARRAY
      this.callToArray.push(whereTo);
      this.returnToArray.push(returnTo);

      if (reqMethod != "GET" || reqMethod != "POST") { reqMethod = "GET"; }
      this.reqMethodArray.push(reqMethod);
    },

    callQueue : function(){
      // CHECK THE QUEUE AND SEND THE NEXT CALL IN LINE
      if(!this.inCall && this.callToArray.length > 0){
        // DO WE HAVE ANYTHING IN THE QUEUE?
        if(this.callToArray.length > 0){
          // WE DO, SO GET THE FIRST ITEM IN THE CALL ARRAY AND REMOVE IT
          whereTo = this.callToArray.shift();
          returnTo = this.returnToArray.shift();
          reqMethod = this.reqMethodArray.shift();
          // SEND THAT CALL
          this.doCall(whereTo, returnTo, reqMethod);
        }else{
          // UPDATE DEBUG QUEUE
        }
      }else{
        // UPDATE DEBUG QUEUE
      }
    },

    doCall : function(whereTo, returnTo){
      this.inCall = true;
      var http = this.createRequestObject();
      http.open('get', whereTo);
      // DO WE HAVE A FUNCTION TO CALL ONCE CALL IS COMPLETED?
      if(returnTo.length > 0){
        eval("http.onreadystatechange = " + returnTo);
      }
      // SEND CALL
      http.send(null);
    }
};

setInterval(requestQueue.callQueue, 100);

1 个答案:

答案 0 :(得分:0)

setInterval(requestQueue.callQueue, 100);

callQueue剥离requestQueue方法并将其传递给setInterval。因此callQueue没有提及requestQueue;在回复时,this将设置为window而不是requestQueue,因此评估this.callToArray.length的尝试将导致错误。

JavaScript中的

this无法以您期望的方式运行任何其他语言。有关说明,请参阅this question。如果您只有一个requestQueue实例,则可以引用它而不是使用this,否则您将需要查看函数绑定或闭包。

顺便提一下,我不建议使用UA-string-sniffing来检测要使用的正确XHR对象。请尝试使用功能嗅探:

var r= window.XMLHttpRequest? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

(这也会在启用的IE7 +上使用原生XMLHttp,可能会避免出现ActiveX提示。)