重写ajax方法实现特定情况下跳转登录页面

jQuery(function($){
            // 备份jquery的ajax方法  
            var _ajax=$.ajax;
            // 重写ajax方法,
            $.ajax=function(opt){
                var _success = opt && opt.success || function(a, b){};
                var _error = opt && opt.error || function(a, b){};
                var _opt = $.extend(opt, {
                    success:function(data, textStatus){
                        // 如果后台将请求重定向到了登录页,则data里面存放的就是登录页的源码,这里需要判断(登录页面一般是源码,所以这里只判断是否有html标签)
                        if(data.meta.code == 返回的需要登录的状态码) {
                            alert('请先登录!');
                            window.location.href = "login.html";
                            return;
                        }
                        _success(data, textStatus);  
                  },
                  error:function(data, textStatus){
                    if(data.meta.code == 返回的需要登录的状态码){
                      alert('请先登录!');
                      window.location.href = "login.html";
                      return;
                    }
                    _error(data, textStatus);
                  } 
                });
                return _ajax(_opt);
            };
        });

  

原文地址:https://www.cnblogs.com/lhy-93/p/5976671.html