我正在尝试使用数据库创建登录页面,但我的按钮在单击时不会执行任何操作,即使它应该带我进入下一页(index2.html)。即使在控制台中也没有显示任何内容,所以我不知道它出了什么问题。
Javascript代码
var response ="";
function plogin(){
var credentials = new Object();
credentials.username= document.getElementById("user").value;
credentials.password = document.getElementById("password").value;
var request = new XMLHttpRequest();
request.open("POST","/userlogin", true);
request.setRequestHeader("Content-Type","application/json");
request.onload=function(){
response = JSON.parse(request.responseText);
document.getElementById("loginform").style.display="none";
if (response.message =="1"){
window.location = "index2.html?username=" + credentials.username;}
else{
document.getElementById("msg").textContent = response.message;}
登录表单
<form id = "loginform" onclick="plogin()">
<label style="color: white;">Username:</label>
<input type="text" style="border-style: solid; border-width:5px; border-color: slategrey;" placeholder="Jon" id="user" name="username">
<br>
<label style="color: white;">Password:</label>
<input type="password" style="border-style: solid; border-width:5px; border-color: slategrey;" id="password" name="password">
<br>
<br>
<input type="button" class = "btn btn-secondary" value="Login">
</form>
两个代码都在同一个 html 页面中
用户登录代码(js)在Postman中工作
userlogin(request, respond){
var username = request.body.username;
var password = request.body.password;
var msg="";
var sql = "SELECT user.password FROM restaurant_review.user WHERE username = ?";
db.query(sql, [username], function(error,result){
if(error){
throw error;
}
else{
if(result.length > 0){
if(password == result[0].password){
msg ="1";
console.log(msg);
}
else{
msg = "FAIL";
console.log(msg);
}
}
else{
msg = "USER NOT FOUND";
console.log(msg);
}
respond.json(prepareMessage(msg));
}
});
```we
最佳答案
尝试在 HTML 中进行更改 <button type="submit">...</button>
而不是<input type="button" class = "btn btn-secondary" value="Login">
关于javascript - onclick 按钮不执行任何操作;未调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180851/