weixin_33682719 2014-02-27 20:53
浏览 29

进行多个ajax调用

I'm trying to run multiple AJAX calls on the same page and seem to be having trouble. I'm new to this so I don't really understand what's going on. I have a drop down menu and I want it to update the content in two different places when the selection changes. Each of these works on their own but when I try running them together it only updates whichever script I run last. Any help would be greatly appreciated

<script>
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","../php/get_org.php?q="+str,true);
xmlhttp.send();
}
</script>

<script>
function list(str)
{
if (str=="")
  {
  document.getElementById("list").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("list").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","../php/list_org.php?q="+str,true);
xmlhttp.send();
}
</script>
  • 写回答

1条回答 默认 最新

  • weixin_33711641 2014-02-27 21:23
    关注

    The reason is simple, you are using same global variable for both requests xmlhttp. Use var when declaring variables like this var xmlhttp = new XMLHttpRequest();.

    Your code initializes xmlhttp and requests for some page. Before the request is done you run some another function, which uses xmlhttp again. It is reinitialized and new onreadystatechange handler is set and another request is made. So only the last response handler set is actually executed.

    评论

报告相同问题?