1.js中判断字符串是否为json
function isJSONOrObject(str) { if (typeof str == 'string') { try { var obj = JSON.parse(str); if (typeof obj == 'object' && obj) { return true; } else { return false; } } catch (e) { return false; } } return true; }
(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,{ error:function(XMLHttpRequest, textStatus, errorThrown){ //错误方法增强处理 fn.error(XMLHttpRequest, textStatus, errorThrown); }, success:function(data, textStatus){ //成功回调方法增强处理 fn.success(data, textStatus); } }); _ajax(_opt); }; })(jQuery);
var token = window.localStorage.getItem('tokenInfo'); var _ajax = $.ajax; $.ajax = function(opt) { 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, { error : function(XMLHttpRequest, textStatus, errorThrown) { //if(XMLHttpRequest.status!==200){ // alert('数据接口报错,状态码:'+XMLHttpRequest.status+'') //} fn.error(XMLHttpRequest, textStatus, errorThrown); }, success : function(data, textStatus, XMLHttpRequest) { if (isJSONOrObject(data)) { var res = JSON.parse(XMLHttpRequest.responseText); if (res.status == '40301' || res.status == '40101') { if (window !== top) { top.location.href = "login.html" } else { window.location.href = "login.html" } } } fn.success(data, textStatus, XMLHttpRequest); }, headers : { Authorization : token, // sid: sid } }); return _ajax(_opt); };