2

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

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);               
        }
    });                                           
}

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

4

2 回答 2

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 正在谈论这样的事情,但更强大。不过,这应该是一个很好的例子,可以帮助您入门。

于 2013-07-22T04:16:02.320 回答
0

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

于 2013-07-22T03:43:22.450 回答