2011-03-07 127 views
10

檢查我的服務器是否通過JavaScript聯機的最快方法是什麼?Javascript:檢查服務器是否在線?

我嘗試了以下AJAX:

function isonline() { 
    var uri = 'MYURL' 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET",uri,false); 
    xhr.send(null); 
    if(xhr.status == 200) { 
     //is online 
     return xhr.responseText; 
    } 
    else { 
     //is offline 
     return null; 
    } 
} 

的問題是,如果服務器脫機它永遠不會返回。如何設置超時時間,以便在一定時間後沒有返回時,我可以假定它處於脫機狀態?

回答

23

XMLHttpRequest不起作用的跨域。相反,我會加載您希望快速回來一個小<img>,看着onload事件:

function checkServerStatus() 
{ 
    setServerStatus("unknown"); 
    var img = document.body.appendChild(document.createElement("img")); 
    img.onload = function() 
    { 
     setServerStatus("online"); 
    }; 
    img.onerror = function() 
    { 
     setServerStatus("offline"); 
    }; 
    img.src = "http://myserver.com/ping.gif"; 
} 

編輯:清理我的答案。在同一個域上可以使用XMLHttpRequest解決方案,但如果您只想測試以查看服務器是否處於聯機狀態,則img加載解決方案是最簡單的。沒有必要混淆超時。如果你想使代碼看起來就像是同步的,這裏有一些對你的語法糖:

function ifServerOnline(ifOnline, ifOffline) 
{ 
    var img = document.body.appendChild(document.createElement("img")); 
    img.onload = function() 
    { 
     ifOnline && ifOnline.constructor == Function && ifOnline(); 
    }; 
    img.onerror = function() 
    { 
     ifOffline && ifOffline.constructor == Function && ifOffline(); 
    }; 
    img.src = "http://myserver.com/ping.gif";   
} 

ifServerOnline(function() 
{ 
    // server online code here 
}, 
function() 
{ 
    // server offline code here 
}); 
+1

很好找到了,但是如果我沒有記錯的話,你必須將它附加到DOM上,因爲如果你不這樣做,所有的瀏覽器都不會加載它。編輯:你可能想使用'onerror',因爲這將執行時,圖像不存在:http://jsfiddle.net/8ZP9r/ – pimvdb 2011-03-07 20:07:17

+0

@pimvdb - 很好!用'onerror'建議好!我會更新我的答案。 – gilly3 2011-03-07 20:12:58

+0

您的AJAX建議似乎無法正常工作。仍然在線下掛起。 – Skizit 2011-03-07 20:17:55

0

使用XMLHttpRequest,然後檢查它是否失敗。不知道這是否可以跨域使用。

1

進行ajax調用,其結果將告訴。

+0

我試了一下,不工作: http://stackoverflow.com/questions/36007060/show-waiting- page-while-server-reboots – Black 2016-03-15 13:12:30