背景介绍:做了一个简单的登录页面,如图。当输入用户名,密码点击登录,会发送ajax post请求,执行登录流程。
但是每次请求完http://localhost:8070/login(ajax请求) 都会再请求http://localhost:8070/ (当前的登录页面)
问题原因,经过网上搜索终于找到了答案,问题出在HTML文件上,原因是我把刚才所有的元素都放在了一个<form>标志的表单里面了,<form>里面的<button>元素默认type=submit, 所以每次点击登录button后都会执行提交表单的操作,表单操作默认有刷新页面的功能
解决方法,将上述所有元素外层的<form>标签去掉或者换成<div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
账号:<input id="idusername" type="text" name="username" aria-label="手机号或邮箱" placeholder="手机号或邮箱" required/> <br>
密码:<input id="idpassword" type="password" name="password" aria-label="密码" placeholder="密码" required/><br>
<button id="idlogin">登录</button>
</form>
<script>
$(document).ready(function(){
$("#idlogin").click(function(){
$.ajax({
type : 'post',
url: "/login",
context: "json",
data:{
username: $("#idusername").val(),
password: $("#idpassword").val()
},
success: function(data){
if (data.code != 0){
console.log(data.msg);
alert(data.msg);
}
else{
console.log(data.msg);
window.location.replace("home");
}
}});
})
</script>
</body>
</html>
至此问题解决了,都是些新手容易犯的问题,让大家见笑了。
谢谢!