繁体   English   中英

Ajax在页面加载时被调用4次

[英]ajax being called 4 times on page load

首先,我沉迷于jQuery,但我想创建一些无框架且尽可能轻巧的东西,所以我很讨厌自己。

我有这个代码:

    function ajax(url)
{
var xmlhttp;
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)
    {
        console.log(xmlhttp.responseText);
    }
   else
        console.log( "error");
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

我用以下方法在脑海中称呼过一次

ajax("url");

但是,我在控制台中看到3个“错误”日志,第四个是rsponseText。

谁都知道为什么会发生这种情况,我该如何避免呢? 我的页面上没有其他脚本。

是每个州的onreadystatechange调用。...有关更多信息, 请访问http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

尝试这个

if (xmlhttp.readyState==4) {
  if(xmlhttp.status==200) {
    console.log(xmlhttp.responseText);
  } 
  else {
     console.log('error');
  }
}
xmlhttp.onreadystatechange=function()

此回调用于超过readystate 4和200的情况。尝试将xmlhttp.status添加到错误消息中,例如

function ajax(url)
{
var xmlhttp;
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)
    {
        console.log(xmlhttp.responseText);
    }
   else
        console.log( "error - readyState: "+xmlhttp.readyState);
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

多次调用ajax(url) ,但调用xmlhttp.onreadystatechange

它不是错误,也不是错误,您看到的是就绪状态更改事件,始终登录else块。 httpObject中不仅有成功和失败状态。

在这里检查

如您所见,有4个状态,只有xmlhttp.readyState==4 && xmlhttp.status==200表示实际成功,请求完成,也没有服务器错误。

这是因为readyState将从1移到4 int(即在其他浏览器中为小)。

尝试:

xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    console.log(xmlhttp.responseText);
   else if(xmlhttp.readyState==4)
        console.log( "error");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM