XHR抛出超时错误并且不执行onTimeout事件

时间:2017-05-11 21:32:16

标签: javascript ajax xmlhttprequest

我正在编写一个本机JavaScript应用程序,我每分钟都会向多个唯一的服务器发出同步的AJAX请求。当服务器脱机时,我希望我的程序通过注册到XHR.ontimeout事件的函数来处理它。

下面是我写的一个快速JS示例来演示我的问题。监控控制台,您会看到有时对离线地址的请求会触发ontimeout事件。其他时候发生ERR_CONNECTION_TIMED_OUT。我希望有一个超时处理程序,每次调用我的函数并且服务器处于脱机状态时执行。

<!DOCTYPE html>
<html>
<TITLE>Timeout Error Demo</TITLE> 
<body>
<script>
var i=0;
var xhr;
function main(){
   console.log('Main run #'+i);
   i++;
   xhr=new XMLHttpRequest();
   xhr.open("GET", "http://1.1.1.1", true);   //this address is always offline
   xhr.timeout=2000;
   xhr.ontimeout=function(){
      console.log("timed out");
   }
   xhr.onreadystatechange=function(){
      if (xhr.readyState==4 && xhr.status==200){
         console.log("done");
      }
   }
   xhr.send(null);
   setTimeout(main,5000);
}
main();
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

它是.ontimeout,而不是.onTimeout。或.addEventListener("timeout", …)