Summary:
jQuery has become the most common js library in projects and the favorite library for front-end development. Below is the Ajax that encapsulates jQuery in the project, shared with everyone.
Code:
},
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(';') < 0 ? str : str.replace(reg, function(chars) {
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 request error message
*Example: 500 error
*Return error message format
*{
* code: 500,
* info: System exception
*}
*/
$(document).ajaxError(function(evt, req, settings){
If(req && (req.status === 200||req.status === 0)){ return false; }
var msg = 'Error:';
If(req && req.responseJSON){
var json = req.responseJSON;
msg = json.code||'';
msg = json.info||'System exception, please try again';
}else{
msg = 'System exception, please try again';
}
alert(msg);
});
Summary:
When executing an Ajax request, you only need to call the ajaxSettings function, as follows:
The above is the entire content of this article, I hope you all like it.