標籤:
摘要:
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(‘;‘) < 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 請求錯誤提示*例如: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: ‘‘}))
Ajax請求全域配置