+ -
当前位置:首页 → 问答吧 → 同时发两个Ajax异步请求,返回的结果混乱了。

同时发两个Ajax异步请求,返回的结果混乱了。

时间:2011-09-21

来源:互联网

var is_make_completed = false;
var make_cont_count = 0;

这是一个Ajax请求,循环发送,一秒钟一次,称为A请求
function loadSccContent()
{
  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  alert("scc_content:"+xmlhttp.responseText);
  if (document.getElementById("compiler_output").innerHTML != xmlhttp.responseText) {
  document.getElementById("compiler_output").innerHTML = xmlhttp.responseText;
  make_cont_count = 0;
  } else {
  make_cont_count += 1;
  }
  return ;
  //document.getElementById("compiler_output").value=xmlhttp.responseText;
  }
  }
  branch_id = document.getElementById("compiler_compilerBranch").value
  xmlhttp.open("GET","/ajax/scccontent/{{user.name}}/"+branch_id+"?t=" + Math.random(),true);
  xmlhttp.setRequestHeader("If-Modified-Since","0");
  xmlhttp.send();
}
function timeoutMake()
{
//alert(make_cont_count);
  loadSccContent();
  if ((is_make_completed == false)&&(make_cont_count < 100)) {
  setTimeout("timeoutMake()",1000);
  }
}

下面是第二个请求,只发送一次,返回结果本来应该是几分钟以后,称为B请求。
function makeBranchAjax()
{
  is_make_completed = false;
  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  //alert(xmlhttp.responseText);
  alert("make was completetd !");
  is_make_completed = true;
  return ;
  }
  }
  branch_id = document.getElementById("compiler_compilerBranch").value
  xmlhttp.open("GET","/ajax/make/{{user.name}}/"+branch_id+"?t=" + Math.random(),true);
  xmlhttp.setRequestHeader("If-Modified-Since","0");
  xmlhttp.send();
}

同时调用了两个函数,两个都是异步,A请求能够正常运行并收到结果,但是B请求等待一段时间后收到的结果却是A请求返回的结果,并且一连收到了3遍。
function updateAndMakeAjax()
{
makeBranchAjax();
timeoutMake();
}
如果只运行B请求,也能收到正确结果。或者B请求同步,也可以收到正确结果,但两个同时请求结果就混乱了。

作者: qianbbo   发布时间: 2011-09-21

试试:
xmlhttpA = new XMLHttpRequest();
...
xmlhttpB = new XMLHttpRequest();

作者: slowhand   发布时间: 2011-09-21

继续路过~

作者: trista_career   发布时间: 2011-09-21

引用 1 楼 slowhand 的回复:

试试:
xmlhttpA = new XMLHttpRequest();
...
xmlhttpB = new XMLHttpRequest();


这样竟然真可以。但是明明是局部变量,为什么会互相影响,公用?

作者: qianbbo   发布时间: 2011-09-21

热门下载

更多