当前位置:   article > 正文

web开发 ajax请求 页面无法跳转

web开发 ajax请求 页面无法跳转

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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
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("请求发送失败..");
	
	    }
	});
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/652414
推荐阅读
相关标签
  

闽ICP备14008679号