建立互联网连接后重定向网页

时间:2013-03-20 19:10:01

标签: javascript jquery html

我正在为工作建立网页自助服务终端。当计算机启动时,它会立即加载自助服务终端,但连接到网络大约需要一分钟。用户看到的第一件事是连接错误,因为自助服务终端试图访问实时页面,但还没有互联网。自助服务终端浏览器使用 Chrome。

为了防止出现初始错误,我正在尝试创建一个本地托管的网页,用于检查互联网连接并等待一个建立。然后它重定向到实况页面。

这是最初的离线本地托管页面。它应该从这里重定向到实时页面。显然,在Chrome浏览器中,navigator.onLine仅会检查Chrome是否设置为“在线模式”'但实际上并没有测试实时连接。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Kiosk Splash</title>
  <link rel=stylesheet type="text/css" href="jquery/css/ui-lightness/jquery-ui-1.10.2.custom.css">
  <script src="jquery/js/jquery-1.9.1.js"></script>
  <script src="jquery/js/jquery-ui-1.10.2.custom.js"></script>
</head>
<body>
<div id="dialog" style="text-align:center;">
    <p>
        <font font face="verdana" size="5">The Kiosk is establishing a connection to the network...</font>
    </p>
    <div id="progressbar" style="width: 50%; margin: 0 auto;"></div>
</div>
<script>
$( "#dialog" ).dialog({ minWidth: 1000 });
$(".ui-dialog-titlebar-close", this.parentNode).hide();
$( "#progressbar" ).width(800);
$( "#progressbar" ).progressbar({
  value: false
});
while(true){
    if(navigator.onLine){
        window.location.replace("http://stackoverflow.com");
        break;
    }
}
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

我不知道navigator.onLine它是如何运作的。  但它应该尝试连接到服务器并继续尝试,直到它连接到服务器。连接重定向后

      function connect(){
      try{
        $.ajax({url:"http://itunes.apple.com/search?term=metallica", // any url which return json
        success: function(){
        location.href = "http://google.com"  
     },
     error: function(e){
         location.href = "http://google.com";
     }, 
       dataType:"json"
   });
}catch(e){
     console.log(e);         
    setTimeout(connect, 5000);
}
} 
connect();

答案 1 :(得分:0)

如果navigator.online无效,请手动执行此操作。

可能是通过查看您是否可以ping服务器来检查连接。为此,请设置尝试检索数据的ajax调用。如果它恢复成功,那么你就连接了!然后,您可以重定向到新页面。

$(function() {
  var myVar=setInterval(function(){ pingServer(); }, 1000),
      urlOnServer = "http://www.google.com",
      urlOfHomePage = "http://www.yahoo.com";

  function pingServer() {
    $.ajax({
      url: urlOnServer,
      data: null,
      dataType: 'json',
      success: function(result) {
        window.location = urlOfHomePage;
      }
    });
  } 
});