在开发应用中我们经常用到ajax,有时候我们需要在ajax执行的时候做一些重复的动作,此时我们就可以重新改写ajax原本的一些方法:
/*
自定义ajax 方法jquery-1.10.2.js
*/
//将原ajax放到_ajax中
_ajax = $.ajax;
$.ajax = function (cfg) {
cfg._beforeSend = cfg.beforeSend;
cfg.beforeSend = function (res) {
//自定义功能
showLoader();//显示
//在执行原本的beforeSend()
if (cfg._beforeSend != null)
cfg._beforeSend(res);
}
cfg._complate = cfg.complete;
cfg.complete = function (res) {
//自定义功能
hideLoader();//隐藏
//在执行原本的complate()
if (cfg._complate != null)
cfg._complate(res);
}
//将原ajax 中的success方法保存为_success
cfg._success = cfg.success;
cfg.cache = false;
//重写ajax的success方法
cfg.success = function (res) { //此方法做自己想做的
if (res.toString().indexOf("No access, please login again")>-1)//无访问权限
{
$("#layout_body").html("");
$("#layout_body").append(res);
return;
}
//如果我们在前面没有return,在这里我们将后台
//返回的数据重新放入原先ajax
if (cfg._success !== null)
cfg._success(res);
}
_ajax(cfg);
}
//以下需要引用jquery.mobile-1.4.5.min.js ,jquery.mobile-1.4.5.min.css
//显示加载器
function showLoader() {
//显示加载器.for jQuery Mobile 1.2.0
$.mobile.loading('show', {
text: '加载中...', //加载器中显示的文字
textVisible: true, //是否显示文字
theme: 'a', //加载器主题样式a-e
textonly: false, //是否只显示文字
html: "" //要显示的html内容,如图片等
});
}
//隐藏加载器
function hideLoader() {
//隐藏加载器
$.mobile.loading('hide');
}
Ajax中的方法都可以按照上面的方式,自定义实现功能。