XMLHTTPRequest with a time-out condition
In a XMLHTTPRequest
, how to use time-out condition such that if there is no response from the server for a fixed amount of time (say 5 seconds) then it should display an error message?
In other words, the request should wait for 5 seconds, if there is no response from the server then it should display a message saying "Time out. Please try again later". It would be better if the code can work for both Synchronous and Asynchronous.
The following code I am using without time-out condition.
function开发者_运维百科 testXMLHTTP()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else if(xmlhttp.readyState < 4)
{
document.getElementById("myDiv").innerHTML="Loading...";
}
}
xmlhttp.open("GET","abcd.php",true);
xmlhttp.send();
}
If you're able to use an external library for your project, you might consider it: jQuery's ajax module allows you to specify a timeout for a request. There's no built-in way to handle timeouts with an XMLHTTPRequest
object in most browsers (except, apparently, IE8+), so you'll need to set a timeout that will check the state of the request after a period of time. This answer to a similar question explores that particular solution more thoroughly, but I still recommend using jQuery if you can.
Here is a clean timeout solution for XHR that I made for an ajax polling system:
function doRequest() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Process request.
}
}
xmlhttp.open("GET", "/your/script", true);
xmlhttp.send();
setTimeout(function() {
if (xmlhttp.readyState < 4) {
// Timeout !
xmlhttp.abort();
}
}, 3000);
}
The good thing about it is that you can call it multiple times and each timeout stays independent. (for example you can call this function every second and after three seconds only the first request will timeout).
精彩评论