我是nodejs的初学者,我正在尝试将响应从nodejs发送到客户端上的ajax。一切工作正常,但问题是在客户端收到了响应,打开了一个新页面,并在该页面上显示了响应。这意味着无法实现Ajax的核心功能。我希望ajax响应显示在同一页面上。请帮忙!! 下面是我的服务器代码:
app.post('/auth',function(req, res){
console.log(req.body);
var username=req.body.username;
var password=req.body.password;
var obj={};
if(username&&password){
connection.query('select * from signup where username=? and password=?',[username,password],function(err, result){
if(err) throw err;
if(result!=0)
{
req.session.loggedin=true;
req.session.username=username;
return res.redirect('/home');
}
obj={'message':'Incorrect Username and/or Password'};
obj=JSON.stringify(obj);
res.send(obj);
});
}
});
这是我的客户端代码。我希望响应显示在ID为“ wrongdetail”的标签内,但是正在另一页上打印。 下面是我的jquery ajax调用:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#submitbut').click(function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost:3000/auth',
success: function(response) {
$('#wrongdetail').html("<b>"+response.message+"</b>");
}
});
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
</head>
<body>
<div class="login-form">
<h3>Sign In</h3>
<form action="auth" method="post" class="form-content">
<label for="username"><b>Username</b></label>
<input type="text" name="username" placeholder="Enter Username ..." id="usernm" required>
<label for="password"><b>Enter Password</b></label>
<input type="password" name="password" placeholder="Enter Password ..." id="passwd" required>
<label for="wrong" id="wrongdetail"></label>
<button id="submitbut">Login</button>
</form>
</div>
</body>
</html>