Ajax请求三次都不起作用,然后就起作用了

Ajax request not working three times and then works

本文关键字:不起作用 然后 起作用 三次 请求 Ajax      更新时间:2024-05-24

我的页面上有多个JavaScript ajax请求。现在,在一个特定的ajax调用(由onclick事件触发)上,我得到了3条背靠背的错误消息。在检查request.readyState时,我发现每次出现错误时,它的就绪状态分别为1、2和3,然后它就工作了(显然readyState=4)。

这是我发送给服务器的ajax请求:

function fetch(parameter){
var myrequest=new ajaxRequest()
myrequest.onreadystatechange=function(){
if (myrequest.readyState==4){    //This property is not equal to "4" for 3 calls
   if (myrequest.status==200 || window.location.href.indexOf("http")==-1){ 
       // Code to be executed for successful call
       }
   }
else{
    alert("Error in Request. Request State is: " + myrequest.readyState);
}
}
myrequest.open("GET", url, true)
myrequest.send(null)
}

在触发onclick事件时,我得到的错误如下:

请求中出错。请求状态为:1
请求中出错。请求状态为:2
请求中出错。请求状态为:3

请求可能有什么问题?

这些是XMLHTTPRequest(ajax)状态,其中:

1=>加载

2=>加载

3=>交互式

4=>准备好

在4,ajax请求被认为是完整的,并且可以访问返回的数据。

您应该放弃else条件。