如何使用jquery以编程方式检查Internet连接的可用性

[英]how to programmatically check availability of internet connection using jquery


I am developing android phonegap application.When i run the application without internet connection,it is force closed.so,I need to check the internet connection in the dom,before calling the ajax using jquery/javascript

我正在开发android phonegap应用程序。当我运行没有互联网连接的应用程序时,它是强制关闭的。所以,我需要检查dom中的互联网连接,然后使用jquery / javascript调用ajax

Here is my sample code:

这是我的示例代码:

var a=navigator.onLine;
 if(a){
  alert('online');
$.ajax({
            type: "GET",
            url: url, 
            dataType: 'json',
            async: true, 
            cache: false,
            success: function(data){ 

                alert('success');
            },
            error: function(e){

                alert('error');
            }
    });
 }else{
  alert('ofline');
 }

But Am always getting the alert('online'),even when there is no internet connection.Please kindly guide me.Thanks in Advance

但即使没有互联网连接,我总是得到警报('在线')。请引导我。谢谢你提前

2 个解决方案

#1


8  

As you specified in a tag, you can't access hardware specs without PhoneGap API, and to check the Available connection all you need is implement the Connection

正如您在标签中指定的那样,如果没有PhoneGap API,您将无法访问硬件规格,并且只需检查可用连接即可实现连接

The connection object gives access to the device's cellular and wifi connection information.

连接对象可以访问设备的蜂窝和wifi连接信息。

function checkConnection() {
    var networkState = navigator.network.connection.type;

    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection';

    alert('Connection type: ' + states[networkState]);
}

checkConnection();

Full Example available in PhoneGap Docs

PhoneGap Docs中提供的完整示例

#2


2  

Maybe you could use the device's network connection state property:

也许您可以使用设备的网络连接状态属性:

var a = (navigator.network.connection.type != Connection.NONE);

Also see the "Connection" API

另请参阅“连接”API


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/02/28/f216fcdf5a6c679d274df21bd0ce9a61.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号