如何在jQuery Mobile中检测设备的互联网连接

joe*_*der 7 javascript jquery jquery-ui jquery-mobile

我正在使用HTML5,CSS3,jQuery Mobile,jQuery UI,ASP.NET,C#和一些jQuery插件为调查创建这个简单的移动网页.其中一个要求是显示弹出/对话框(javascript警报或jQuery移动对话框,如果是jQuery UI对话框,则更好),只要设备没有互联网连接(特别是Android),就会通知用户.目前我有这个代码:

<link rel="stylesheet" href="../Scripts/jqueryui/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="../Scripts/jquery.mobile-1.1.0.css" />
<script src="../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery.mobile-1.1.0.js" type="text/javascript"></script>
<script src="../Scripts/jqueryui/jquery.min.js" type="text/javascript"></script>
<script src="../Scripts/jqueryui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.validate.js" type="text/javascript"></script>

<script type="text/javascript">
    var online = window.navigator.onLine;
    if (!online) {
        alert('Please check your internet connection and try again.');
    }
    function checkInternet() {
        var online = window.navigator.onLine;
        if (!online) {
            alert('Please check your internet connection and try again.');
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

然后我把JavaScript函数放在表单的onsubmit事件上:

<form id="frmSurvey" runat="server" class="validate" onsubmit="checkInternet()">
Run Code Online (Sandbox Code Playgroud)

当我在台式机/ PC浏览器上查看但它根本无法在移动设备上运行时,它正在工作.jQuery Mobile错误加载页面.

因为,这不是我调整jQuery Mobile文件的要求,注释了错误加载页面消息部分,它不再出现了.我已经尝试过谷歌搜索任何相关主题,但没有找到任何相关主题.

我真的很难让这成为可能.请帮帮我们!

提前致谢!

Gaj*_*res 10

很少有解决方案可以满足您的需求.

解决方案1

这个解决方案需要jQuery,因为你使用的是jQuery Mobile,它将作为一个魅力.

$.ajaxSetup({
    timeout: 1, // Microseconds, for the laughs.  Guaranteed timeout.
    error: function(request, status, maybe_an_exception_object) {
        if(status == 'timeout')
            alert("Internet connection is down!");
    }
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看有关ajaxSetup的官方文档.

解决方案2

这个有点棘手,因为它取决于HTML5浏览器的实现.

基本上你需要检查这个值是真还是假:

window.navigator.onLine - 如果用户处于脱机状态,则为false.

工作示例:http://jsfiddle.net/Gajotres/VXWGG/1/

测试:

  • Windows Firefox

  • Windows谷歌浏览器

  • Windows IE9和IE10

  • Android 4.1.1 Chrome

  • iPad 3 Safari

  • iPad3 Chrome

  • 根据[this](https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.onLine#Browser_compatibility),[this](http://stackoverflow.com/a/2384227/1469208)和[this](http://stackoverflow.com/a/4813406/1469208),`navigator.onLine`,虽然是HTML5的一部分,**仅在Chrome和基于WebKit的浏览器中得到正确支持**!其他浏览器返回`true` always或 - 当'离线'模式被禁用时返回'true`,当启用时返回'false`,无论实际连接如何. (2认同)