2012-12-28 40 views
0

我想下面的函數進行每x秒調用,所以我沒有刷新我的網頁。如何檢查互聯網連接,而無需刷新我的整個頁面

var rq = new XMLHttpRequest(); 
rq.open('GET', "SAME DOMAIN ADDRESS", true); 
rq.onreadystatechange = function() { 
    if(rq.readyState === 4) { 
     if(rq.status === 200) { 
     clearTimeout(xmlHttpTimeout); 
window.location.href = "Tracker.html"; // if internet connection found, redirect. 
     } else { 
     } 
    } 
}; 
rq.send(""); 
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000); 
function ajaxTimeout(){ 
    rq.abort(); 
// IF no internet connection found, call this whole javascript function/code AGAIN in 5 seconds! to check for internet connection 
} 

基本上,我想檢查互聯網連接,而無需刷新我的整個頁面 - 如果有,然後重定向到Tracker.html

+0

AJAX - May The Force be with you! –

+2

[同源策略](https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript)。閱讀它。 – epascarello

+1

當然,當你知道答案的時候,實際的答案可能已經改變了。即連接可能會隨機出現,所以重定向可能會失敗。 –

回答

1

檢查navigator.onLine是真還是假。

+0

哇!這是強大的,從來沒有聽說過它。謝謝! – Homie

1

最好的方法是使用setTimeout

function callMe() { 
    // Some Code 
    setTimeout(callMe, 1000); 
} 

callMe(); 

您的代碼將看起來像:

var rq = new XMLHttpRequest(); 

rq.onreadystatechange = function() { 
    if(rq.readyState === 4) { 
    if(rq.status === 200) { 
     window.location.href = "Tracker.html"; // if internet connection found, redirect. 
    } else { 
     setTimeout(rq.send, 5000); 
    } 
    } 
}; 

rq.send(); 

如果您想檢查客戶端是否已連接,則還可以使用描述爲here的新的在線和離線事件。

+0

所以問題是......如何將上面的JavaScript代碼插入到callMe函數中?我在問,因爲上面的代碼中有更多的功能..... – Homie

+0

我編輯了我的代碼,但我強烈建議您使用navigator.onLine,除非您不必支持舊版瀏覽器。 – Gpx

0

Ajax解決方案只能在同一個域中使用。但是,在同一個域中,您可能不需要測試服務器是否在線。通過navigator.onLine,它將指示互聯網是否可以訪問,但仍然無法訪問相應的服務器。

訣竅是嘗試加載目標服務器的和錯誤,則在5秒後重試的圖像。當圖像加載成功後,可以完成重定向。

<html> 
    <header> 
    </header> 
    <body> 
    <script type="text/javascript"> 
    var img = new Image(); 
    var ping = function() { img.src = "http://www.somedomain.com/valid_image.jpg"; } 
    ping(); 

    img.onerror = function(e) { 
     console.log('error'); 
     setTimeout(function() { 
     ping(); 
     }, 5000); 
    } 

    img.onload = function(e) { 
     console.log('YES'); 
     window.location.href = "http://www.google.com"; 
    } 
    </script> 

    </body> 
</html>