第二个请求收到第一个仍在处理的请求

时间:2013-07-22 02:53:03

标签: javascript

我有一个请求系统,其中两个不相关的函数正在向我的服务器发出请求。但问题是反应不正确让我逐步解释发生了什么:

A background function makes a request to the server
Server processes task 1
A second unrelated background function makes a request to the server
Client recieves response of task 1
The second function recieves that response that was for the first function. 
The first function never gets a response.

现在我不知道如何解决它,但我知道我需要分开区分它们,所以这里没有冲突。

这是我当前处理请求内容的代码:

function call_back(result,func){
        if(typeof(func) != 'undefined' || func != false){       
            func(result);
        } else {
            return false;
        }
}

function caller(url,cfunc){
        if (window.XMLHttpRequest)
          {
            xmlhttp=new XMLHttpRequest();
          }
        else
          {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
            xmlhttp.onreadystatechange=cfunc;
            xmlhttp.open("GET",url,true);
            xmlhttp.send();
}

function call_file(url,func){ //handles html files (not json_encoded)
    caller(url,function(){
        if ( xmlhttp.readyState== 4 && xmlhttp.status== 200 ){
            call_back(xmlhttp.responseText,func);
        }
    });
}

function call_data(url,func,JsonBool){ //handles json_encoded data 
    caller(url,function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
        call_back(JSON.parse(xmlhttp.responseText),func);               
        }
    });                                           
}

我可以对我的功能做些什么,以防止这种行为?

2 个答案:

答案 0 :(得分:1)

以下是一个如何构建代码的示例 - 我已经使用过它,它可以工作,但可以进行改进。

function Ajax(url, callback,args){
  var xhttp = init();
  xhttp.onreadystatechange = process;

  function init() {
    if(window.XMLHttpRequest)
      return new XMLHttpRequest();
    else if (window.ActiveXObject)
      return new ActiveXObject("Microsoft.XMLHTTP");
  }
  function process() {
    if (xhttp.readyState==4 && xhttp.status==200) {
      if (callback) callback(xhttp.responseText,args);
      else return xhttp.responseText;
    }
  }
  this.Get=function(){
    xhttp.open("GET", url, true);
    xhttp.send(null);
  }
}

使用它:

var url = '/someurl';
var ajax = new Ajax(url,yourCallback,parameters); 
ajax.Get();

我相信DRobinson正在谈论类似的事情,但更强大。这应该是一个很好的例子,让你开始。

答案 1 :(得分:0)

在我看来,好像你正在为xmlhttp使用全局/窗口变量。如果是这种情况,第二个呼叫的某些部分将覆盖第一个。考虑使用面向对象的方法,或者将它们实例化为不同范围内的变量。