ajax 302 错误无法跳转

1.问题当cas登录失败之后如果继续执行ajax请求会报 302 重定向错误,但是因为是ajax请求,所以浏览器不会自动跳转,需要做处理。

1.自己重写ajax方法:不推荐

var Ajax = function() {
    var that = this;
    // 创建异步请求对象方法
    that.createXHR = function() {
        if (window.XMLHttpRequest) { // IE7+、Firefox、Opera、Chrome 和Safari
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE6 及以下
            var versions = [ 'MSXML2.XMLHttp', 'Microsoft.XMLHTTP' ];
            for (var i = 0, len = versions.length; i < len; i++) {
                try {
                    return new ActiveXObject(version[i]);
                    break;
                } catch (e) {
                    // 跳过
                }
            }
        } else {
            throw new Error('浏览器不支持XHR对象!');
        }
    }
    // 初始化数据方法
    that.init = function(obj) {
        // 初始化数据
        var objAdapter = {
            method : 'get',
            data : {},
            success : function() {
            },
            complete : function() {
            },
            error : function(s) {
                alert('status:' + s + 'error!');
            },
            async : true
        }
        // 通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题
        that.url = obj.url + '?rand=' + Math.random();
        that.method = obj.method || objAdapter.method;
        that.data = that.params(obj.data) || that.params(objAdapter.data);
        that.async = obj.async || objAdapter.async;
        that.complete = obj.complete || objAdapter.complete;
        that.success = obj.success || objAdapter.success;
        that.error = obj.error || objAdapter.error;
    }
    // get方法
    that.get = function(obj) {
        var xhr = that.createXHR(); // 创建XHR对象
        that.init(obj);
        if (that.async === true) { // true表示异步,false表示同步
            // 使用异步调用的时候,需要触发readystatechange 事件
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) { // 判断对象的状态是否交互完成
                    that.callback(obj, this); // 回调
                }
            };
        }
        // 若是GET请求,则将数据加到url后面
        that.url += that.url.indexOf('?') == -1 ? '?' + that.data : '&'
            + that.data;
        // 在使用XHR对象时,必须先调用open()方法,
        // 它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
        xhr.open(that.method, that.url, that.async);
        xhr.send(null); // get方式则填null
        if (that.async === false) { // 同步
            that.callback(obj, this); // 回调
        }
    }
    // 请求成功后,回调方法
    that.callback = function(obj, xhr) {
        console.log("ajax 请求http code值:" + xhr.status)
        if (xhr.status == 200) { // 判断http的交互是否成功,200表示成功
            obj.success(xhr.responseText); // 回调传递参数
        } else {
          // 如果请求有问题就跳转到首页去登录
            console.log('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
            top.location.href = "/home";
        }
    }
    // 数据转换
    that.params = function(data) {
        var arr = [];
        for ( var i in data) {
            // 特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
        }
        return arr.join('&');
    }
    return {
        get : that.get,
    }
}

这里项目里面本身都是使用的jquery的ajax请求,如果所有请求都走我自己定义一套ajax去处理302的话,那么改动量比较大,因此选择继续使用 jquery的ajax,那么如何处理这个错误的问题呢?

ajax给我们提供了一个ajaxSetup方法,可以对回调做预处理,我们只需要覆写这个方法就可以处理ajax的返回值的逻辑了,代码如下:

/**
 * 处理 ajax 302 错误问题
 */
$.ajaxSetup({
    //请求方式,默认为get
    type:'post',
    //请求成功后触发
    success: function () {
        console.log('成功')
    },
    //请求失败遇到异常触发
    error: function () {
        console.log('失败')
    },
    //完成请求后触发。即在success或error触发后触发
    complete: function (XMLHttpRequest,status) {
        if(status === 'error'){
        	// 关键在这里,如果返回值为error那么久直接跳转到指定页面
        	// 这里使用top可以解决iframe嵌套之后,父页面不跳转的情况
            top.location.href = "/home";
        }
    },
})
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值