一. 问题背景
后台:使用SSM,controller方法使用返回值为ModelAndView进行前端页面跳转
前端:发送ajax请求,交给controller处理,用ModelAndView进行跳转
二. 解决方法
如果是使用ajax提交请求,那么用ModelAndView.setViewName()
是跳转不成功的。除非在controller处理好数据后,==在ajax的回调中使用window.location.href = 'xxx';
进行跳转,如下:
html页面
//给加入购物车按钮绑定点击事件
$("#saveBtn").on("click", function(){
layer.msg("hehe");
$.ajax({
url: '/UsedProduct/checkUser',
dataType: 'json',
success: function(result){
console.info(result);
if(result.data==null){
window.location.href = '/UsedProduct/templates/layuimini/page/login.html';
}
}
});
});
controller方法
@ResponseBody
@RequestMapping(value="/checkUser")
public Map<String,Object> checkLoginUser(HttpServletRequest request){
Map<String, Object> map = new HashMap<String, Object>();
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
map.put("code", 0);
map.put("msg", "操作成功");
map.put("count", 1);
map.put("data", user);
return map;
}