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

时间:2012-12-04 13:12:49

标签: javascript ajax

首先,我沉迷于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个“错误”日志,第4个是rsponseText。

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

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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是。

答案 2 :(得分:0)

它不是一个错误,而且你看到的是onready statechange事件并且始终登录else块并不是错误。 httpObject中不仅有成功和失败状态。

请检查here

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

答案 3 :(得分:0)

因为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");
}