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.

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler