请使用下面的代码帮助我。我正在尝试使用javascript和nedb数据库验证登录。我做错了什么。
的login.html
<form name="login" onSubmit="return validateForm();" action="home.html" method="post">
<input type="text" name="user" id="user" placeholder=" Enter Username" required/>
<br>
<input type="password" name="pass" id="pass" placeholder="Enter Password" required/>
<input type="submit" value="Login">
</form>
loginvalidate.js
此代码用于验证,检查和查询数据库中的用户名和密码,但它没有。在对话框出现后单击确定后,它将进入home.html。
const database = require('../scripts/logindb');
function validateForm() {
var user = document.loginform.user.value;
var pass = document.loginform.pass.value;
database.getAdmin(function(admin){
var username = admin.username;
var password = admin.password;
if ((user == username) && (pass == password)) {
return false;
}
else {
alert ("Error , please check your username and password");
return false;
}
});
}
logindb.js
var Datastore = require('nedb');
db = new Datastore({ filename: 'db/admin.db', autoload: true });
exports.addAdmin = function(firstname, lastname, username, password)
{
var admin = {
"firstname": firstname,
"lastname": lastname,
"username": username,
"password": password
};
db.insert(admin, function(err, newDoc) {
if (err) throw err;
console.log("Table created!");
db.close();
});
};
exports.getAdmin = function(fnc) {
db.find({}, function(err, docs) {
fnc(docs);
});
}
答案 0 :(得分:0)
将event
作为参数添加到validateForm
函数调用中:
<form name="login" onSubmit="return validateForm(event);" action="home.html" method="post">
然后在validateForm
函数内使用preventDefault()
传入的event
参数:
function validateForm(event) {
event.preventDefault();
// other code here
return false;
}
同样require
不是常规JavaScript的一部分,它在NodeJS中用于加载模块。
您需要在HTML中加载javascript文件:
<script src="../scripts/logindb"></script>