检查设备(智能手机)是否在线或离线的最简单方法是什么。我正在使用phonegap,jquery mobile。我找到了这个。
document.addEventListener("online", yourCallbackFunction, false);
我想要做的是检查互联网连接并决定从互联网或设备本地数据库中获取数据。
if(deviceoffline)
getDataFromLokalDatabase();
else
getDataFromInternet();
检查设备(智能手机)是否在线或离线的最简单方法是什么。我正在使用phonegap,jquery mobile。我找到了这个。
document.addEventListener("online", yourCallbackFunction, false);
我想要做的是检查互联网连接并决定从互联网或设备本地数据库中获取数据。
if(deviceoffline)
getDataFromLokalDatabase();
else
getDataFromInternet();
This is the code using native phonegap code:
function checkInternet() {
var networkState = navigator.connection.type;
if(networkState == Connection.NONE) {
onConnexionError();
return false;
} else {
return true;
}
}
您可以使用navigator.onLine
:
var isOffline = 'onLine' in navigator && !navigator.onLine;
if ( isOffline ) {
//local db
}
else {
// internet data
}
但请注意,如果navigator.onLine
不支持isOffline
将始终是错误的
使用 Jquery 进行 ajax 调用并检查错误代码,如果错误代码为 0,则设备处于脱机状态
$.ajax({
//your ajax options
error: function (request) {
if (request.status == 0) {
alert("you're offline");
}
}
});
Beware, while navigator.onLine is the simplest solution, it does not behave consistently on all browsers. On Chrome it will tell you that it is online if you have a LAN cable in, even if you have no internet.
You can use the cordova plugin network-information
You can also try to make an AJAX request to your server; usually you want to know if you are offline because in that case you cannot communicate with the server, so "offline" often means "not able to communicate with the server" (which can be also caused by your server being offline). Playing with timeouts or several requests is also useful if you need to check bandwidth or link quality.
Offline does not mean the same for every use case, you first need to know which of the above techniques is best suited for you, then implement one or several of them.
What I want to do is to check the Internet connection and decide about to get the data from the internet or from the device local database.
It seems that checking the link with your server through a request is the best option for you.
本机 onLine 有点不稳定,尤其是在 web 应用程序环境中.. 但可以用于 pageLoad 的初始检查,但是它有点没用,就好像你到了那个时候你有互联网连接一样。
尝试 ajax 的东西要可靠得多。