jquery已经成为项目中最常见的js库,也是前端开发最喜欢使用的库。下面是在项目中封装了jquery的ajax,分享给大家。
代码:
复制代码 代码如下:
// ajax 请求参数
var ajaxsettings = function(opt) {
var url = opt.url;
var href = location.href;
// 判断是否跨域请求
var requesttype = 'jsonp';
if (url.indexof(location.host) > -1)
requesttype = 'json';
requesttype = opt.datatype || requesttype;
// 是否异步请求
var async = (opt.async === undefined ? true : opt.async);
return {
url: url,
async: async,
type: opt.type || 'get',
datatype: requesttype,
cache: false,
data: opt.data,
success: function(data, textstatus, xhr) {
/*
*如果datatype是json,怎判断返回数据是否为json格式,如果不是进行转换
* 成功数据通用格式
* {
* code: 200,
* data: [],
* success: true // 成功
* }
* 失败返回的数据
* {
* code: 200,
* info: 'error',
* success: false // 失败
* }
*/
if((requesttype === 'json' || requesttype === jsonp) && typeof(data) === string) {
data = json.parse(data);
}
if(data.success) {
opt.success(data);
} if(opt.error) {
opt.error(data);
}
},
error: function(xhr, status, handler) {
if (opt.error)
opt.error();
}
};
};
function unescapeentity(str) {
var reg = /&(?:nbsp|#160|lt|#60|gt|62|amp|#38|quot|#34|cent|#162|pound|#163|yen|#165|euro|#8364|sect|#167|copy|#169|reg|#174|trade|#8482|times|#215|divide|#247);/g,
entity = {
' ' : ' ',
' ' : ' ',
' ' '>' : '>',
'&62;' : '>',
'&' : '&',
'&' : '&',
'' : '',
'' : '',
'¢' : '¢',
'¢' : '¢',
'£' : '£',
'£' : '£',
'¥' : '¥',
'¥' : '¥',
'€' : '?',
'€' : '?',
'§' : '§',
'§' : '§',
'©' : '©',
'©' : '©',
'®' : '®',
'®' : '®',
'™' : '™',
'™' : '™',
'×' : '×',
'×' : '×',
'÷' : '÷',
'÷' : '÷'
};
if (str === null) {
return '';
}
str = str.tostring();
return str.indexof(';') return entity[chars];
});
}
// 转换html的实体
$.ajaxsetup({
global : true,
cache : false,
converters : {
'text json' : function(response){
return jquery.parsejson(unescapeentity(response));
}
}
});
/*
*ajax 请求权限异常
* 用户权限错误跳转登陆页
* 404错误跳转404页面
*/
$(document).ajaxcomplete(function(evt, req, settings){
if(req && req.responsejson){
var json = req.responsejson;
if(json.code === 403 && json.info === 'perm error' && !json.success){
window.location.href = location.protocol + '//' + location.hostname;
return;
}
if(json.code === 404 && !json.success) {
window.location.href = location.protocol + '//' + location.hostname + '/404.html';
}
}
});
/*
*ajax 请求错误提示
*例如:500错误
*返回错误信息格式
*{
* code: 500,
* info: 系统发生异常
*}
*/
$(document).ajaxerror(function(evt, req, settings){
if(req && (req.status === 200||req.status === 0)){ return false; }
var msg = '错误:';
if(req && req.responsejson){
var json = req.responsejson;
msg += json.code||'';
msg += json.info||'系统异常,请重试';
}else{
msg = '系统异常,请重试';
}
alert(msg);
});
小结:
在执行ajax请求时只需要调用ajaxsettings函数即可,如下:
复制代码 代码如下:
$.ajax(ajaxsettings({
url: '',
data: ''
}))
以上所述就是本文的全部内容了,希望大家能够喜欢。
