JQuery Mobile检测互联网连接是否可用

10

通过我的 Web 应用程序,检测我的移动设备是否有互联网连接的最佳方法是什么?

5个回答

22

2
这使我在线状态即使我离线。`<body onload='updateIndicator()' ononline='updateIndicator()' onoffline='updateIndicator()'> <!--检查网络连接--> <script><br/> function updateIndicator() { document.getElementById('indicator').textContent = navigator.onLine ? '在线' : '离线'; } </script> <p>网络状态: <span id="indicator">(未知状态)</span></body>` - Anuj Verma
尝试这个:function hasConnection() { if (window.navigator.connection.type === Connection.NONE) { return false; } return true; } - Mimouni

4
一个选择是 更改Ajax设置,添加特定的 timeout,然后添加一个 error 处理程序,查找 textStatus(第二个参数)为 'timeout'
当超时发生时,可能是因为网络连接不稳定或您的网站已经宕机。
使用ajaxSetup为所有请求设置选项默认值:
$.ajaxSetup({
    timeout: 1, // Microseconds, for the laughs.  Guaranteed timeout.
    error: function(request, status, maybe_an_exception_object) {
        if(status != 'timeout')
            alert("YOU BROKE IT");
        else
            alert("OH NOES TEH INTARWEBS ARE DOWN!!!!!1one");
    }
});

@Satch,我使用了我提供的链接为您组装了一个功能性但不太有用的示例。如果您希望了解更多信息,我强烈建议参考文档,因为我所做的一切都是基于文档和我提供的任务描述。 - Charles
这并不真正起作用。使用window.navigator.onLine的答案才是正确的。 - DATEx2
@Satch3000你能给我展示一个实际的例子吗?或者我们该如何实现集中管理? - Rahul Rajput

2

在简单的JS代码中,这可以完成,因为所有特色设备都不支持JS。然而,对于基于Web的应用程序来说,这是使用最少代码的方法。

online = window.navigator.onLine;
if (navigator.onLine) {
  alert('you are online');
} else {
  alert('you are offline');
}

1

如果您想每隔X秒检查连接。

        $(document).ready(function() {
            setInterval(function(){
                var isOnline = navigator.onLine;
                if (isOnline) {
                    console.log("Connected");
                }
                else {
                    console.log("Not Connected");
                }
            }, 30000); // 10000 = 10 seconds, check for connection every 30 seconds
        });

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接