在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();
}
看看http://stackoverflow.com/questions/1018705/how-to-detect-timeout-on-an-ajax-xmlhttprequest-call-in-the-browser –
我懷疑這是可能的同步請求,因爲JavaScript是單線程的。 –