如何使用jquery编程方式检查互联网连接的可用性 [英] how to programmatically check availability of internet connection using jquery
问题描述
我在开发Android的PhoneGap application.When我运行的应用程序没有互联网连接,这是力closed.so使用jQuery / JavaScript的调用Ajax出现之前,我需要检查在DOM的互联网连接,
下面是我的示例code:
VAR一个= navigator.onLine;
如果一个){
警报(在线);
$阿贾克斯({
键入:GET,
网址:网址,
数据类型:JSON,
异步:真正的,
缓存:假的,
成功:功能(数据){
警报(成功);
},
错误:函数(E){
警报('错误');
}
});
}其他{
警报('ofline');
}
但我总是得到警报(在线),即使没有互联网connection.Please亲切指导me.Thanks提前
当您在标签规定,你不能访问硬件规格没有的PhoneGap API ,然后检查可用的连接你需要的是实现了连接。
在
连接
对象可以访问该设备的蜂窝和Wi-Fi连接信息。
函数checkConnection(){
VAR networkState = navigator.network.connection.type;
变种状态= {};
国家[Connection.UNKNOWN] ='未知连接;
国家[Connection.ETHERNET] ='以太网连接;
国家[Connection.WIFI] ='WiFi连接;
国家[Connection.CELL_2G] ='细胞2G连接;
国家[Connection.CELL_3G] ='细胞3G连接;
国家[Connection.CELL_4G] ='细胞4G连接;
国家[Connection.NONE] ='无网络连接;
警报(连接方式:+国[networkState]);
}
checkConnection();
完整的例子在 PhoneGap的文档提供
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
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
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
The
connection
object gives access to the device's cellular and wifi connection information.
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
这篇关于如何使用jquery编程方式检查互联网连接的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!