当前位置: 移动技术网 > IT编程>开发语言>Java > 解决Ajax请求时无法重定向的问题

解决Ajax请求时无法重定向的问题

2019年02月28日  | 移动技术网IT编程  | 我要评论

 

今天发现,当使用ajax请求时,如果后台进行重定向到其他页面时是无法成功的,只能在浏览器地址栏输入才能够实现重定向。

ajax默认就是不支持重定向的,它是局部刷新,不重新加载页面。

需要实现的功能是,后台网关拦截请求,看请求中是否存在token.如果不存在就跳转到登录页面。因为大多数请求都是使用ajax.一开始发现无法进行重定向,每次都是返回到ajax的结果处理函数。最终的解决办法如下,需要后台和前端进行处理。

后台:

/**
 *功能描述
 * @author lgj
 * @description  重定向工具类
 * @date 2/27/19
*/
@slf4j
public class redirecutil {

    /**
     *功能描述
     * @author lgj
     * @description  重定向
     * @date 2/27/19
     * @param:
     * @return:
     *
    */
    public  static void  redirect(requestcontext ctx, string redirecturl){

        try{
            //如果是ajax请求
            if("xmlhttprequest".equals(ctx.getrequest().getheader("x-requested-with"))){
                log.debug("ajax redirect");
                sendredirect(ctx.getresponse(),redirecturl);
            }
            //如果是浏览器地址栏请求
            else {

                log.debug("normal redirect ");
                ctx.getresponse().sendredirect(redirecturl);
            }
        }
        catch(exception ex){
            ex.printstacktrace();
        }

    }


    /**
     *功能描述 
     * @author lgj
     * @description   ajax请求时重定向处理
     * @date 2/27/19
     * @param: 
     * @return: 
     *
    */
    private static void sendredirect(httpservletresponse response, string redirecturl){
        try {
       //这里并不是设置跳转页面,而是将重定向的地址发给前端,让前端执行重定向 //设置跳转地址 response.setheader("redirecturl", redirecturl); //设置跳转使能 response.setheader("enableredirect","true"); response.flushbuffer(); } catch (ioexception ex) { log.error("could not redirect to: " + redirecturl, ex); } } }

前端处理


第一种方式:使用ajax的complete方法


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


            },
//请求完成调用 (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;
          }
      },
    });
})

但是上面有个问题就是,每个ajax都需要编写 comlete 方法,代码复用率低。

 

第二种方法 : 使用全局的complete方法

ajax请求

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


            },
    
        });

全局处理

注意这参数(event, xhr, settings)不能少,否则会报错。

//每一个ajax 请求完成之后都会执行。
$(document).ajaxcomplete(function (event, xhr, settings) { console.log("ajaxcomplete ") redirecthandle(xhr); })


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; }
}

 

也可以将上述前端代码放入一个js文件中,在需要进行重定向的时候引入即可,便可以实现更高的代码复用率。

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文件,src根据据实际情况设置。

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

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网