我想要一个表单在没有互联网连接时返回false。我有一个脚本,当页面加载时检查互联网连接,它工作正常。但是当用户提交并且没有互联网时,它会显示警告权但仍然会尝试提交并显示默认错误网页“无法找到该页面”。
<form action="http://usersite.com/script.php" method="post" name="form1" target="_parent" id="form1" onsubmit="checkConnection()">
检查互联网
<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';
if ((states[networkState]) == states[Connection.NONE])
alert('No Internet Connection');
return false;
}
</script>
答案 0 :(得分:1)
Define Enum
`var NetworkStatusEnum = {
NO_INTERNET_DEVICE : {status:StatusCodes.NO_INTERNET_DEVICE,message:"No Internet connection on the device"},
NETWORK_OK : {status:StatusCodes.NETWORK_FINE,message:"Network fine"}
}`
Write following method
`function isNetworkPresent()
{
var response = {};
var networkState = navigator.connection.type;
var states = {};
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]) {
response = NetworkStatusEnum["NETWORK_OK"];
} else {
response = NetworkStatusEnum["NO_INTERNET_DEVICE"];
}
return response;
}`
Now wherever you want to check for internet call `isNetworkPresent` method
var networkResponse = isNetworkPresent();
if(networkResponse.status == StatusCodes.NETWORK_FINE)
{
//Your code on internet present
}
else
{
//Your code on internet not present
}