2009-10-06 45 views
29

如何向以下脚本添加超时?我希望它显示文本为“Timed Out”超时XMLHttpRequest

var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no) 
var loadedobjects = "" 
var rootdomain = "http://" + window.location.hostname 
var bustcacheparameter = "" 

function ajaxpage(url, containerid) { 
    var page_request = false 
    if (window.XMLHttpRequest) // if Mozilla, Safari etc 
     page_request = new XMLHttpRequest() 
    else if (window.ActiveXObject) { // if IE 
     try { 
      page_request = new ActiveXObject("Msxml2.XMLHTTP") 
     } catch (e) { 
      try { 
       page_request = new ActiveXObject("Microsoft.XMLHTTP") 
      } catch (e) {} 
     } 
    } else 
     return false 
    document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>' 
    page_request.onreadystatechange = function() { 
     loadpage(page_request, containerid) 
    } 
    if (bustcachevar) //if bust caching of external page 
     bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime() 
    page_request.open('GET', url + bustcacheparameter, true) 
    page_request.send(null) 
} 


function loadpage(page_request, containerid) { 
    if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) 
     document.getElementById(containerid).innerHTML = page_request.responseText 
    else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1)) 
     document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments' 
} 
+0

一个很好的回答这个问题是在这里:http://stackoverflow.com/questions/1018705/how-to-detect-timeout-on-an-ajax-xmlhttprequest-call-in-浏览器 – 2011-08-26 21:11:39

回答

73

例如使用XMLHttpRequest对象的超时属性。

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; // Set timeout to 4 seconds (4000 milliseconds) 
xhr.ontimeout = function() { alert("Timed out!!!"); } 
xhr.send(json); 

上面的代码适合我!

干杯

+1

编辑代码:超时处理程序应设置为“ontimeout”,而不仅仅是“超时”。 (在搜索相同的东西时发现此帖,[MSDN](http://msdn.microsoft.com/en-us/library/ie/cc304105%28v=vs.85%29.aspx)确认)。 – 2012-01-24 21:28:50

+0

@erikvold'timeout' /'ontimeout'在Firefox中也支持,从Firefox 12.0开始:https://developer.mozilla.org/en/xmlhttprequest#Browser_compatibility – 2012-07-05 15:14:29

+11

只需要注意任何人看到XHR的间歇错误, IE10 - 必须在xhr.open语句之后设置xhr.timeout值。如果在我看到IE10偶然抛出一个错误之前设置了超时值。 – paj 2013-08-14 07:04:37