2011-08-21 134 views
3

XMLHTTPRequest中,如何使用超時條件,以便如果服務器沒有響應一段固定的時間(例如5秒),則應該顯示錯誤消息?帶有超時條件的XMLHTTP請求

換句話說,請求應該等待5秒鐘,如果服務器沒有響應,那麼它會顯示一條消息,說「超時,請稍後再試」。如果代碼可同時適用於同步和異步,那將會更好。

以下代碼我沒有使用超時條件。

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();  
} 
+4

看看http://stackoverflow.com/questions/1018705/how-to-detect-timeout-on-an-ajax-xmlhttprequest-call-in-the-browser –

+0

我懷疑這是可能的同步請求,因爲JavaScript是單線程的。 –

回答

3

如果你能使用外部庫爲你的項目,你可能會認爲這:jQuery's ajax module允許你指定的請求超時。在大多數瀏覽器中,除了顯然IE8 +外,沒有內置的方法來處理對象XMLHTTPRequest的超時,因此您需要set a timeout來檢查一段時間後請求的狀態。 This answer to a similar question更徹底地探索了特定的解決方案,但如果可以的話,我仍然建議使用jQuery。

1

下面是XHR乾淨超時的解決方案,我一個AJAX投票系統進行:

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); 
} 

關於它的好處是,你可以調用它多次,每次超時保持獨立。 (例如,您可以每秒調用一次該函數,三秒後只有第一個請求會超時)。