2017-02-25 83 views
0

我嘗試了很多事情來捕捉這段代碼的錯誤,但不知何故我無法捕捉到它的錯誤。你能捕捉到連接錯誤嗎?

我試過trycatch(err)方法,但是彈出錯誤。無法找到有關如何捕獲服務器連接錯誤的文章。他們彈出我的控制檯日誌,但我似乎無法趕上他們。以下是我迄今爲止所嘗試的......以及我嘗試的方式之一。

function timrec(){ 
try{ 
var time; 
var inter1sec = setInterval(frame, 1000); 
function frame() { 
var xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     time = JSON.parse(this.responseText); 
     document.getElementById("demo").innerHTML = "Date is: "+time.d+"-"+time.m+"-"+time.y+" <br> Time is: " +time.h+":"+time.mi+":"+time.s+ " <br> day of the week is: "+ time.dow + "<br>"; 

}; } 

xmlhttp.open("GET", "date.php",true); 
xmlhttp.send(); 

} 
} 
catch(err){ 
alert("Warning! Connection error! Server might be down!"); 
} 
} 

我使用的代碼,間隔獲取服務器的時間,但似乎無法當我嘗試刷新我的WAMP的服務器,以模擬服務器連接失敗趕上它的錯誤。

它甚至有可能趕上?

如果有可能你可以分享?如果不是......那麼這將是一個失敗。不管是那個,還是我的教授只是給我一個詭計問題。不會是第一次壽。 :/

+0

'如果(this.readyState == 4 && this.status == 200){'如果不這樣做,那麼它的錯誤。你可能只想要一個else語句 – mehulmpt

+0

準確地說你的意思是「連接錯誤」是什麼意思?你可以說得更詳細點嗎? –

+0

@Mehul Mohan嘗試過,但它只是一遍又一遍地重複它約3次,然後發佈相同的錯誤。 :/和anied,我認爲它已經在問題中給出了。 – Arkonsol

回答

2

使用此代碼:

var xmlhttp = new XMLHttpRequest(); 

xmlhttp.open("GET", "http://www.google.com", true); 

xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState === 4) { // request completed. we have some results 
     if (xmlhttp.status === 200) { 
      console.log(xmlhttp.responseText) 
     } else { 
      console.log("Oops", xmlhttp.statusText); 
     } 
    } 
}; 

xmlhttp.send(null); 
+0

感謝兄弟。這實際上工作。現在我知道我錯過了什麼......再次感謝你! – Arkonsol