Solve the problem that Ajax requests cannot be redirected

Posted by whitmard on Sun, 01 Dec 2019 07:18:21 +0100

Today, it is found that when using Ajax requests, if the background redirection to other pages is not successful, only in the browser address bar input can achieve redirection.

Ajax does not support redirection by default. It is a partial refresh and does not reload the page.

The function to be implemented is that the background gateway intercepts the request to see if there is a token in the request. If not, jump to the login page. Because most of the requests are using Ajax. At first, it was found that redirection could not be performed, and each time it was returned to the result processing function of Ajax. The final solution is as follows, which needs to be handled in the background and front end.

Backstage:

/**
 *Function description
 * @author lgj
 * @Description  Redirection tool class
 * @date 2/27/19
*/
@Slf4j
public class RedirecUtil {

    /**
     *Function description
     * @author lgj
     * @Description  redirect
     * @date 2/27/19
     * @param:
     * @return:
     *
    */
    public  static void  redirect(RequestContext ctx, String redirectUrl){

        try{
            //If it is Ajax request
            if("XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))){
                log.debug("ajax redirect");
                sendRedirect(ctx.getResponse(),redirectUrl);
            }
            //If it's a browser address bar request
            else {

                log.debug("normal redirect ");
                ctx.getResponse().sendRedirect(redirectUrl);
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }

    }


    /**
     *Function description 
     * @author lgj
     * @Description   Ajax Redirect processing on request
     * @date 2/27/19
     * @param: 
     * @return: 
     *
    */
    private static void sendRedirect(HttpServletResponse response, String redirectUrl){
        try {
       //This is not to set the jump page, but to send the redirected address to the front end for redirection
//Set jump address response.setHeader("redirectUrl", redirectUrl); //Set jump enable response.setHeader("enableRedirect","true"); response.flushBuffer(); } catch (IOException ex) { log.error("Could not redirect to: " + redirectUrl, ex); } } }

Front-end processing


The first way: using Ajax's complete method


 $.ajax({
            type: "post",
            url: "/auth/token/check",
            success: function(data,status){
                console.log("/token/check Return status : "+status)


            },
//Request complete call
(XHR, TS){ console.log("complete"); var url = XHR.getResponseHeader("redirectUrl"); console.log("redirectUrl = " + url); var enable = XHR.getResponseHeader("enaleRedirect");
                console.log("enableRedirect = " + enable);
                if((enable == "true") && (url != "")){ 

var win = window;

         while(win != win.top){
      win
= win.top;
        }
         win.location.href
= url;
          }

      },

    });
})

But the above problem is that every ajax needs to write "comlete" method, and the code reuse rate is low.

 

The second method: use the global complete method

ajax request

 $("#NON-TOKEN").click(function () {
        $.ajax({
            type: "post",
            url: "/auth/token/check",
            success: function(data,status){
                console.log("/token/check Return status : "+status)


            },
    
        });

Global processing

Note that this parameter (event, xhr, settings) cannot be less, otherwise an error will be reported.

//Every Ajax request is executed after it is completed.
$(document).ajaxComplete(function (event, xhr, settings) { console.log("ajaxComplete ") redirectHandle(xhr); })


function
redirectHandle(xhr) {
  //Get parameters returned by background
var url = xhr.getResponseHeader("redirectUrl"); console.log("redirectUrl = " + url); var enable = xhr.getResponseHeader("enableRedirect"); if((enable == "true") && (url != "")){ var win = window; while(win != win.top){ win = win.top; } win.location.href = url; }
}

 

You can also put the above front-end code into a js file, which can be introduced when redirection is needed, so as to achieve higher code reuse rate.

redirect.js

function  redirectHandle(xhr) {

    var url = xhr.getResponseHeader("redirectUrl");
    console.log("redirectUrl = " + url);

    var enable = xhr.getResponseHeader("enableRedirect");

    if((enable == "true") && (url != "")){
        var win = window;
        while(win != win.top){
            win = win.top;
        }
        win.location.href = url;
    }

}

$(function () {

    $(document).ajaxComplete(function (event, xhr, settings) {
        console.log("ajaxComplete  adffdafadsaf")
        redirectHandle(xhr);
    })
})

js file is introduced, and src is set according to the actual situation.

<script src="/common/redirect.js"></script>

Topics: Java less