使用ajax发送POST请求后ModelAndView不能跳转页面

前台使用ajax提交数据,后台用ModelAndView,setViewName不能跳转

解决方法(转载):Ajax发送POST请求SpringMVC页面跳转失败https://www.cnblogs.com/boycelee/p/6243646.html

以下为转载:

问题描述:因为使用的是SpringMVC框架,所以想使用ModelAndView进行页面跳转。思路是发送POST请求,然后controller层中直接返回相应ModelAndView,但是这种方法不可行。那我们的解决方法是什么呢?

我的解决方案是,将判断前移,什么意思呢?服务器值返回Map数据,对应页面跳转状态,将逻辑代码写在js代码中。代码如下:

使用

window.location.href = “/iswust2hand/index.jsp”;
进行相应页面跳转

为什么使用Ajax向SpringMVC中Controller层发送POST请求无法无论我们使用return “index.jsp”、 转发 、 重定向 还是 ModelAndView,都无法解决页面跳转的问题。
出现这个问题发的原因是什么呢?

原因:
这就要从Ajax的原理说起,Ajax实际上就是通过XMLHttpRequest来发送请求对象向服务器发送异步请求,从服务器获取数据,然后使用JS来操作DOM而更新页面。
也就是说,服务器端返回的是纯文本流,可以是xml格式,html格式,js格式,也可以是字符串格式,但总结一句话,客户端获取ajax异步获取结果后,不是直接显示在页面上,而是必须要先由js处理,完成之后才能显示在页面。

这就可以解释我们的问题了,当Ajax请求后,返回的只能是字符流,不是页面。所以要使页面跳转,我的解决方案是,将数据用Map返回,然后将数据交由js去解决,
window.location.href = “/iswust2hand/index.jsp”; 跳转就可以。

参考:http://www.ithao123.cn/content-2251957.html

@ResponseBody
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public Map<String, Object> userRegister(@RequestBody User user, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        User userInfo = userLoginService.userRegister(user);
        System.out.println(user.getNumber());
        if (userInfo != null)
            map.put("code", "0");
        else
            map.put("code", "1");

        return map;

    }
<script type="text/javascript">
    $(document).ready(function() {
        $("#login_user").click(function() {
            var username = $("#login_account").val();
            var pass = $("#login_userPwd").val();
            var user = {
                number : username,
                password : pass
            };//拼装成json格式  

            $.ajax({
                type : "POST",
                url : "http://localhost:8080/iswust2hand/2hand/user/login",
                data : JSON.stringify(user),
                contentType : 'application/json;charset=utf-8',
                dataType : 'json',
                success : function(data) {

                      if (data.code == '0') {
                        window.location.href = "/iswust2hand/index.jsp";
                        alert("欢迎使用西科二手平台!");
                    }else{
                        alert("密码错误,请确认后重新登录!");
                    }  

                },

                error : function(data) {
                    alert("出错:" + data.code);
                }

            });

        });
    });
</script>
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值