The page does not jump after the ajax request is redirected (using an interceptor)

First, the problem of ajax redirection.

The default ajax does not support redirection, because ajax itself is a partial refresh and does not reload the page. If you need to use redirection, you can use the following methods:

The first step: back-end code transformation.

Determine whether redirection is required in the backend (in most cases, interceptors).

Eg: Session expiration judgment, when it is judged that the session has expired, first judge whether the request is an Ajax request.

method:

@Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object arg2) throws Exception {
        User u = (User) request.getSession().getAttribute("USER");
        String type = request.getHeader("X-Requested-With");// XMLHttpRequest
        if (u == null) {
            // 重定向
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
            //response.sendRedirect(contextPath+"/index.jsp");
            // System.err.println("sendRedirect");
            // Forward
            if (StringUtils.equals("XMLHttpRequest", type)) {
            // ajax请求
                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                response.setHeader("CONTEXTPATH", basePath+"index.jsp");

                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;

            } else {
                response.sendRedirect(basePath+"index.jsp");
                return false;
            }
        }
        return true;
    }
    
        Step 2: Transform the ajax attribute in the previous paragraph.

        Use the $.ajaxSetup() method to uniformly add the operations performed after the request execution ends to the ajax method.

            $.ajaxSetup( {
        //Set the execution action after the end of the ajax request
        complete :
        function(XMLHttpRequest, textStatus) {
        // Get the response header through XMLHttpRequest, sessionstatus
            var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
            if (sessionstatus == "TIMEOUT") {
                var win = window;
                while (win != win.top){
                    win = win.top;
                }
                win.location.href= XMLHttpRequest.getResponseHeader("CONTEXTPATH");
            }
        }
    });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324397758&siteId=291194637