ajax重写和参数编码
重写$.ajax
(function($){
//首先备份下jquery的ajax方法
var _ajax=$.ajax;
//重写jquery的ajax方法
$.ajax=function(opt){
//备份opt中beforeSend,error和success方法
var fn = {
error:function(XMLHttpRequest, textStatus, errorThrown){},
success:function(data, textStatus){},
beforeSend:function(XHR){}
}
if(opt.error){
fn.error=opt.error;
}
if(opt.success){
fn.success=opt.success;
}
if(opt.beforeSend){
fn.beforeSend=opt.beforeSend;
}
//对get请求中的参数base64加密后赋值给p(后台定义,后台处理)
if(opt.type == 'GET'){
var arr = opt.url.split('?');
if(arr.length > 1){
//解决有些url参数值中带有?
if(arr.length == 2){
opt.url = arr[0] + '?p=' + Base.encode(arr[1]);
}else{
var urlStr = '';
for(var i = 1;i<arr.length;i++){
urlStr = urlStr + arr[i];
}
opt.url = arr[0] + '?p=' + Base.encode(urlStr);
}
}else{
if(opt.data){
var json = opt.data,str='';
for(var key in json){
str+=key + '=' + json[key] + '&';
}
opt.url = opt.url + '?p=' + Base.encode(str.substring(0,str.length-1));
opt.data = '';
}
}
};
//扩展增强处理
var _opt = $.extend(opt,{
error:function(XMLHttpRequest, textStatus, errorThrown){
//错误方法增强处理
fn.error(XMLHttpRequest, textStatus, errorThrown);
},
success:function(data, textStatus){
//成功回调方法增强处理
fn.success(data, textStatus);
},
beforeSend:function(xhr){
//提交前回调方法
//跨站请求伪造保护
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
xhr.setRequestHeader("X-CSRFToken", csrftoken);
fn.beforeSend(xhr);
},
complete:function(XHR, TS){
//请求完成后回调函数 (请求成功或失败之后均调用)。
$("#ajaxInfo").remove();;
}
});
return _ajax(_opt);
};
})(jQuery);