我正在开发android phonegap应用程序。当我运行没有互联网连接的应用程序时,它被强制关闭。所以,我需要检查dom中的互联网连接,然后使用jquery / javascript调用ajax
以下是我的示例代码:
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');
}
但即使没有互联网连接,我总是得到警报('在线')。请指导我。谢谢你提前
答案 0 :(得分:8)
正如您在代码中指定的那样,如果没有 PhoneGap API ,则无法访问硬件规格,并且只需检查可用连接即可实现连接
connection
对象可以访问设备的蜂窝和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();
中提供的完整示例
答案 1 :(得分:2)
也许您可以使用设备的网络连接状态属性:
var a = (navigator.network.connection.type != Connection.NONE);