如何检测浏览器中的AJAX(XmlHttpRequest)调用的超时?

我在网上看,但文件很难来。 我们都知道使用浏览器内置的XMLHttpRequest对象的基本AJAX调用(在这里假设一个现代的浏览器):

var xmlHttp = new XMLHttpRequest(); // Assumes native object xmlHttp.open("GET", "http://www.example.com", false); xmlHttp.send(""); var statusCode = xmlHttp.status; // Process it, and I'd love to know if the request timed out 

那么,有没有一种方法可以通过检查浏览器中的XMLHttpRequest对象来检测到AJAX调用超时? 我会被build议做一些像window.setTimeout(function(){xmlHttp.abort()},30000);?

谢谢!

-麦克风

更新:这是一个如何处理超时的例子 :

 var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", "http://www.example.com", true); xmlHttp.onreadystatechange=function(){ if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { clearTimeout(xmlHttpTimeout); alert(xmlHttp.responseText); } } // Now that we're ready to handle the response, we can make the request xmlHttp.send(""); // Timeout to abort in 5 seconds var xmlHttpTimeout=setTimeout(ajaxTimeout,5000); function ajaxTimeout(){ xmlHttp.abort(); alert("Request timed out"); } 

在IE8中,您可以将一个超时事件处理程序添加到XMLHttpRequest对象。

 var xmlHttp = new XMLHttpRequest(); xmlHttp.ontimeout = function(){ alert("request timed out"); } 

我build议不要在你的代码中暗示进行同步调用,并且build议使用javascript框架来做到这一点。 jQuery是最stream行的一个。 它使您的代码更高效,更易于维护和跨浏览器兼容。

一些现代的浏览器(2012)不需要依赖setTimeout就可以做到这一点:它包含在XMLHttpRequest中。 请参阅回答https://stackoverflow.com/a/4958782/698168

 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { alert("ready state = 4"); } }; xhr.open("POST", "http://www.service.org/myService.svc/Method", true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.timeout = 4000; xhr.ontimeout = function () { alert("Timed out!!!"); } xhr.send(json);