问题
I'm new to Cordova and currently working with it. I'm creating a login script at the moment, but when I submit a form it looks like the database won't react.
The following is what I'm trying to do:
- When the API's are loaded, create a table and insert a record.
- When user submits the form, check if the inserted data equals the data of the table.
- If it matches, go to a new page.
I'm not even getting the alert invalid ...
when I inserted something useless. I'm getting the success!
alert when I start-up the app.
HTML:
<form id="login" onsubmit="check_login();" class="form-signin">
<input id="username" type="text" class="form-control" placeholder="Name" required autofocus>
<input id="password" type="password" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Sign in
</button>
</form>
JAVASCRIPT:
var db;
function check_login() {
var username = $("#username").val();
var password = $("#password").val();
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM LOGIN WHERE username=? AND password=?', [username, password], function(tx, results) {
if (results.rows) {
window.location = "main.html";
} else {
alert("Invalid username or password");
}
}, null);
});
}
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS LOGIN');
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGIN (id unique, username, password)');
tx.executeSql('INSERT INTO LOGIN (id, username, password) VALUES (1, "Admin", "Admin")');
}
// Transaction error callback
//
function errorCB(tx, err) {
alert("Error processing SQL: " + err.code);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
回答1:
Solved it ! first i needed to prevent the default event of the submit button. second i didn't think results.row
was enough but this will do if (results.rows.length > 0)
.
The code i use at the moment: works great !
function check_login() {
event.preventDefault(); // cancel default behavior
var username = $("#username").val();
var password = $("#password").val();
db.transaction(function(tx) {
alert(tx + "test");
tx.executeSql('SELECT * FROM LOGIN WHERE username=? AND password=?', [username, password], function(tx, results) {
if (results.rows.length > 0) {
window.location = "main.html";
} else {
alert("Invalid username or password");
}
}, errorCB);
});
}
来源:https://stackoverflow.com/questions/26085181/cordova-websql-onsubmit