How to set up ajax time out?
I have this code to time out ajax call after 40 secs:
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true); xmlhttp.onread开发者_运维技巧ystatechange = showResults;
xmlhttp.send(null);
var httpTimeOut=setTimeout("ajaxTimeout();",40000);
}
function ajaxTimeout() {
xmlhttp.abort();
document.getElementById('errorShow').innerHTML = "Request Timed out";
}
However I am unable to test this due to environment constraints at my place. Can anyone please tell if this is correct or any modifications are required??
Should fix that:
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true);
xmlhttp.onreadystatechange = showResults;
xmlhttp.send(null);
setTimeout(function() { xmlhttp.abort() },40000);
since ajaxTimeout
function can't "see" xmlhttp
variable, but we can use anonymous function to have access to local variables.
Yet another approach is to use jQuery.ajax
so the library would take care of it.
Your code would look like so:
$.ajax({
url: MY_SERVLET,
async: true,
timeout: 40000,
success: function(args) {
// on success code
}
})
精彩评论