如何检测超时的一个AJAX(XmlHtt prequest)在浏览器中调用? [英] How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
问题描述
我在网上寻找,但文件是很难得的。我们都知道基本的AJAX调用使用的内置XMLHtt prequest对象浏览器(假定一个现代浏览器在这里):
I'm looking on the web, but documentation is hard to come by. We all know the basic AJAX call using the browser's built-in XMLHttpRequest object (assume a modern browser here):
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
那么,有没有我可以检测到了AJAX调用超时通过检查XMLHtt prequest对象在浏览器的方法吗?我会建议做类似window.setTimeout(函数(){xmlHttp.abort()},30000);
So, is there a way that I can detect that the AJAX call timed out by inspecting the XMLHttpRequest object in the browser? Would I be advised to do something like window.setTimeout(function() { xmlHttp.abort() }, 30000);?
谢谢!
-Mike
推荐答案
更新:下面的你如何处理超时的例子:
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,您可以添加超时的事件处理程序在 XMLHtt prequest
对象。
In IE8, You can add a timeout event handler to the XMLHttpRequest
object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
我会建议不要使同步调用为您的code暗示,也建议使用JavaScript框架来做到这一点。 jQuery的 是最流行的一种。它使你的code更高效,更易于维护和跨浏览器兼容。
I would recommend against making synchronous calls as your code implies and also recommend using a javascript framework to do this. jQuery is the most popular one. It makes your code more efficient, easier to maintain and cross-browser compatible.
这篇关于如何检测超时的一个AJAX(XmlHtt prequest)在浏览器中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!