Javascript 如何设置ajax超时?
我有以下代码在40秒后超时ajax调用:Javascript 如何设置ajax超时?,javascript,ajax,timeout,settimeout,Javascript,Ajax,Timeout,Settimeout,我有以下代码在40秒后超时ajax调用: if (xmlhttp) { xmlhttp.open("GET", MY_SERVLET, true); xmlhttp.onreadystatechange = showResults; xmlhttp.send(null); var httpTimeOut=setTimeout("ajaxTimeout();",40000); }
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true); xmlhttp.onreadystatechange = showResults;
xmlhttp.send(null);
var httpTimeOut=setTimeout("ajaxTimeout();",40000);
}
function ajaxTimeout() {
xmlhttp.abort();
document.getElementById('errorShow').innerHTML = "Request Timed out";
}
但是,由于我所在的环境限制,我无法对此进行测试。有人能告诉我这是正确的还是需要修改吗???应该解决这个问题:
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true);
xmlhttp.onreadystatechange = showResults;
xmlhttp.send(null);
setTimeout(function() { xmlhttp.abort() },40000);
由于ajaxTimeout
函数无法“查看”xmlhttp
变量,但我们可以使用匿名函数访问局部变量
另一种方法是使用,以便图书馆能够处理它
您的代码如下所示:
$.ajax({
url: MY_SERVLET,
async: true,
timeout: 40000,
success: function(args) {
// on success code
}
})
为了整洁起见,我将该setTimeout函数命名为:var xmlto=setTimeout(…),然后在得到答案时清除它:cleartimout(xmlto);因为让它运行或第二次调用ajax可能会造成一点混乱。