1. 程式人生 > >重寫ajax請求頭

重寫ajax請求頭


(function($){  
    //備份jquery的ajax方法  
    var _ajax=$.ajax;  
      
    //重寫jquery的ajax方法  
    $.ajax=function(opt){
        //備份opt中error和success方法  
        var fn = {  
            error:function(XMLHttpRequest, textStatus, errorThrown){},  
            success:function(data, textStatus){}  
        }  
        if(opt.error){  
            fn.error=opt.error;  
        }  
        if(opt.success){  
            fn.success=opt.success;  
        }  
        //擴充套件增強處理  
        var _opt = $.extend(opt,{

            //在此處設定請求頭
            beforeSend:function(xhr){
                setRequestHeaders(xhr);
            },

           //在此處設定error
            error:function(XMLHttpRequest, textStatus, errorThrown){  
                //錯誤方法增強處理
                var result=null;
                if (XMLHttpRequest.responseText && XMLHttpRequest.responseText !="") {
                    result=$.parseJSON(XMLHttpRequest.responseText);
                }else if (XMLHttpRequest.responseJSON && XMLHttpRequest.responseJSON != "" && XMLHttpRequest.responseJSON != null) {
                    result=$.parseJSON(XMLHttpRequest.responseJSON);
                }
                if (result !=null && result.code == "401") {
                    alert("登入已經超時,請重新登入!",function(){
                        $.removeCookie('jaAuthorization');
                        $.removeCookie('jaloginName');
                        $.removeCookie('japassword');
                        $.removeCookie('jaUserId');
                        $.removeCookie('jaUserType');
                        window.parent.location.href='../login.html';
                    });
                    return ;
                }else if(result !=null &&  result.code == "403"){
                    alert("沒有許可權,請聯絡管理員",function(){
                        
                    });
                    return ;
                }else if (result !=null) {
                    alert(result.desc,function(){});
                    return ;
                }
                fn.error(XMLHttpRequest, textStatus, errorThrown);  
            }
        });  
        _ajax(_opt);  
    };  
})(jQuery);