如果有互联网连接,则检测到JQuery Mobile

时间:2011-04-11 20:00:50

标签: javascript html5 jquery-mobile internet-connection

通过我的网络应用程序检测手机上是否有互联网连接的最佳方法是什么?

5 个答案:

答案 0 :(得分:22)

没有必要的代码 - 它是HTML5 API的一部分。检查window.navigator.onLine的值 - 如果用户离线,则为false

http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state

答案 1 :(得分:4)

选项可能changing the Ajax settings添加特定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");
    }
});

答案 2 :(得分:2)

在简单的JS代码中,这可以做到,因果关系所有特色设备都没有JS支持 但是对于基于Web的应用程序,这是使用

的最小代码
online = window.navigator.onLine;
if (navigator.onLine) {
  alert('you are online');
} else {
  alert('you are offline');
}

答案 3 :(得分: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
        });

答案 4 :(得分:-1)

如果你想要比window.navigator.onLine更具兼容性,可靠性和可定制性的东西,试试我的jQuery插件:http://tomriley.net/blog/archives/111

相关问题