seeway

导航

解决ajax请求默认不支持重定向问题

1,Ajax默认是不支持重定向的,只局部刷新数据,不跳转页面。

2,后台代码处理:

 @RequestMapping("/updateCurrentUser")
    public String updateCurrentUser(HttpServletRequest request, HttpServletResponse response, String type){
        JsonObject json = new JsonObject();
        String url = "";
        if(type.equals("ADMIN_USER")){
            Object s_user1 = request.getSession().getAttribute(Global.SESSION_ADMIN);
            request.getSession().setAttribute("currentUser",s_user1);
            request.getSession().setAttribute(Global.USER_ROLE,"ADMIN_USER");
            url  = "/jsp/console/backstageHome.jsp";
        }
        if(type.equals("MEDIATORS")){
            Object s_user2 = request.getSession().getAttribute(Global.SESSION_MEDIATOR);
            request.getSession().setAttribute("currentUser",s_user2);
            request.getSession().setAttribute(Global.USER_ROLE,"MEDIATORS");
            url =  "/case/listMe";
        }

        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求,需要特殊处理
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            //告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath+url);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }

        return  null;
    }

3.前端代码处理:

var jqxhr;
    //设置ajax请求完成后运行的函数,
    $.ajaxSetup({
        complete:function(){
            if("REDIRECT" == jqxhr.getResponseHeader("REDIRECT")){ //若HEADER中含有REDIRECT说明后端想重定向,
                var win = window;
                while(win != win.top){
                    win = win.top;
                }
                win.location.href = jqxhr.getResponseHeader("CONTENTPATH");//将后端重定向的地址取出来,使用win.location.href去实现重定向的要求
            }
        }
    });

    function updateCurrentUser(type){
        //debugger;
        jqxhr = $.ajax({
            type: "GET",
            async: true,
            url: "../../center/updateCurrentUser?type="+type,
            dataType: "json",
            success: function(data){

            },
            error:function(err){

            }
        });
    }

 

posted on 2018-08-02 17:02  seeway  阅读(1003)  评论(0编辑  收藏  举报