问题描述:因为使用的是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
1 @ResponseBody 2 @RequestMapping(value = "/user/login", method = RequestMethod.POST) 3 public Map<String, Object> userRegister(@RequestBody User user, HttpServletRequest request, 4 HttpServletResponse response) throws ServletException, IOException { 5 Map<String, Object> map = new HashMap<String, Object>(); 6 User userInfo = userLoginService.userRegister(user); 7 System.out.println(user.getNumber()); 8 if (userInfo != null) 9 map.put("code", "0"); 10 else 11 map.put("code", "1"); 12 13 return map; 14 15 }
1 <script type="text/javascript"> 2 $(document).ready(function() { 3 $("#login_user").click(function() { 4 var username = $("#login_account").val(); 5 var pass = $("#login_userPwd").val(); 6 var user = { 7 number : username, 8 password : pass 9 };//拼装成json格式 10 11 $.ajax({ 12 type : "POST", 13 url : "http://localhost:8080/iswust2hand/2hand/user/login", 14 data : JSON.stringify(user), 15 contentType : 'application/json;charset=utf-8', 16 dataType : 'json', 17 success : function(data) { 18 19 if (data.code == '0') { 20 window.location.href = "/iswust2hand/index.jsp"; 21 alert("欢迎使用西科二手平台!"); 22 }else{ 23 alert("密码错误,请确认后重新登录!"); 24 } 25 26 }, 27 28 error : function(data) { 29 alert("出错:" + data.code); 30 } 31 32 }); 33 34 }); 35 }); 36 </script>