1. 具体错误描述
前端登陆时使用ajax进行请求,后端对ajax请求的跳转会出现:后端无错误,但是前端页面无法跳转的现象。
前端:
$(function() {
// 点击登录按钮时,发送ajax请求
$("#login-btn").click(function() {
// 发送ajax请求
$.ajax({
url: "${pageContext.request.contextPath}/login.do",
method: "post",
data: {
"userName": $("#username").val(),
"passWord": $("#password").val()
}
});
});
});
$(function () {
if ("0" == "${isSuccess}") {
$("#error-username").text("账号或者密码有误,请重新登录").css({"color": "red"});
}
})
后端:
@RequestMapping("/login.do")
public ModelAndView login(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
User thisUser = userService.userLogin(user);
if (thisUser == null) {
mv.setViewName("login");
mv.addObject("isSuccess", "0");
} else {
mv.setViewName("index");
request.getSession().setAttribute("user", thisUser);
}
return mv;
}
2. 解决方法
2.1 用<form>
表单,进行提交
<form action="${pageContext.request.contextPath}/login.do" method="post">
<input type="text" name="userName" id="userName" placeholder="邮箱/手机号码/小米ID">
<span id="error-username">填写邮箱、手机号码或者小米ID登录</span>
<input type="password" name="passWord" id="passWord" placeholder="密码">
<span id="error-password">密码不能为空</span>
<input type="submit" id="login-btn" value="登录">
</form>
2.2 前端使用js进行重定向
$("#login-btn").click(function() {
// 发送ajax请求
$.ajax({
url: "/xiaomi/consumer/login/auth",
method: "post",
data: {
"username": $("#username").val(),
"password": $("#password").val()
},
success:function(response) {
console.log("请求发送成功");
console.log(response);
if(response.errorCode === "100") {
// 登录成功
alert("恭喜,用户登录成功!");
window.location = "/xiaomi/index.jsp";
} else {
// 登录失败
$("#error-username").text("账号或者密码有误,请重新登录").css({"color": "red"});
}
},
error: function() {
console.log("请求发送失败..");
}
});
});