当Ajax请求遇到 redirect 跳转

阅读更多

博客地址:http://blog.ifootsteps.com/?p=64

 

在使用ajax请求服务器时,某些情况需要经过身份验证,如果某个用户停留在页面很长时间,导致令牌过期,此时如果访问某些资源,会验证不通过,但页面却不会跳转到登录页面.
这个情况在网上搜索一下发现遇到的人还不少.下面发现几个很好的解释.
The unfortunate truth about AJAX and the 302 redirect is that you can’t get the headers from the return

because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.

With the way XHR is built in general (and in Chrome specifically): XHR is not very flexible, and provides a relatively high-level API, with the same behavior the browser has in all other requests (address bar urls, image source urls, embedded script urls), i.e. redirects are handled transparently. No events will be thrown in the JavaScript alerting you of this redirect or the intermediate 302/301 status codes, you will only receive the final status code and data. Therefore, it is impossible to retrieve the “Location” header from the response, as the final response will not contain the “Location” header.

单词都很简单易懂.另share一下 原文地址:

AJAX redirect dilemma, how to get redirect URL OR how to set properties for redirect request
jQuery and AJAX response header

 

所以无奈下搞出一个方法.

在我们的业务场景下,在服务器端接收到请求后,可以区分是否为ajax请求,所以在区别出是否为ajax请求后,设置如下代码:

//如果是页面请求直接设置为转发,否则为ajax请求设置返回头信息
        if(per.value()==PermissionPolicy.PAGE){
            response.sendRedirect(redirectURL);
        }else{
            response.setIntHeader("REQUIRES_AUTH",1);
            response.setHeader("REQUIRES_AUTH_URL",redirectURL);
        }
        return null;

 在页面因为ajax请求本身就是我们自己封装好的所以只需要加上error时候处理就ok了

$.ajax({
    url : url,
    beforeSend : function(request) {
        request.setRequestHeader("uri", window.location.href);
    },
    type : 'get',
    data : query,
    dataType : 'json',
    error : function( req, status, err) {
        var auth = req.getResponseHeader("REQUIRES_AUTH");
        var auth_url = req.getResponseHeader("REQUIRES_AUTH_URL");
        if(auth == 1 && auth_url){
            window.location.href = auth_url;
        }
        callback([
            {
                datas: '',
                count: 0
            }
        ]);
    },
    success : function(result, textStatus, request) {
        callback(result);
    }
});

 

 

最后分享一句讨厌的话..

Sorry — I hate the “you can’t do this” answers, too, but there are some JavaScript limitations that haven’t quite been ironed out yet.

 

如果其他有解决办法求分享..

你可能感兴趣的:(javascript,ajax,redirect)