我是Cordova的新手,目前正在使用它。我现在正在创建一个登录脚本,但是当我提交表单时,看起来数据库不会做出反应。
以下是我要做的事情:
当我插入无用的东西时,我甚至没有收到警报invalid ...
。我在启动应用程序时收到success!
警报。
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!");
}
答案 0 :(得分:2)
解决了!首先,我需要阻止提交按钮的默认事件。第二,我没想到results.row
就够了,但这样做if (results.rows.length > 0)
。
我目前使用的代码:效果很好!
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);
});
}