Phonegap 没有互联网警报弹出问题

Phonegap no internet alert pop up issue

我在网络上搜索,当应用程序打开时告诉连接类型时我得到了这个脚本。

<script type="text/javascript" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">

// Wait for PhoneGap to load
// 
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
    checkConnection();
}

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]);
}

</script>

但我想让它做的是在没有互联网时显示警报,所以我找到了一个有条件语句但无法工作的脚本

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';

if ((states[networkState]) == states[Connection.NONE])
{
alert("Please check your internet connectivity and try again"); 
}

请有人告诉我出路,我还有一个提交的表格,如果没有互联网提交,我希望该表格也return到同一页面

<form id="loginform" name="loginform" method="POST" action="http://mysite/login.php">

我没有将 states[] 值分配给字符串,而是使用 true/false 并且知道 NONEUNKOWN 都是没有连接的指示符,我这样设置:

    states[Connection.UNKNOWN]  = false;
    states[Connection.ETHERNET] = true;
    states[Connection.WIFI]     = true;
    states[Connection.CELL_2G]  = true;
    states[Connection.CELL_3G]  = true;
    states[Connection.CELL_4G]  = true;
    states[Connection.CELL]     = true;
    states[Connection.NONE]     = false;

那么你可以这样做:

if (states[networkState] === false) {
    //do something
 }

连接到 'offline' 事件,然后在事件触发时显示未连接 message/alert 可能是更好的选择。您可以将它与 'deviceready' 事件触发时显示的消息一起使用。

确保您安装了 org.apache.cordova.network-information 插件才能正常工作。

The offline event fires when a previously connected device loses a network connection so that an application can no longer access the Internet. It relies on the same information as the Connection API, and fires when the value of connection.type becomes NONE.

document.addEventListener("offline", onOffline, false);

function onOffline() {
    // Handle the offline event
}

参考: https://github.com/apache/cordova-plugin-network-information/blob/master/doc/index.md#offline