1.基於 query zepto 的ajax
直接擼程式碼,廢話不多說
ajax: function(setting) {
//假JSON時用get請求
setting.type = setting.url.lastIndexOf('.json') > -1 ? 'GET' : setting.type;
var defaultSetting = {
dataType: setting.dataType || 'json', //伺服器返回json格式資料
type: setting.type || 'post', //HTTP請求型別
contentType: setting.contentType || 'application/x-www-form-urlencoded;charset=UTF-8',
timeout: setting.timeout || 20000, //超時時間設定為20秒;
async: true,
cache: false, //不快取
success: function(resp, status, xhr, settings) {
if(status == "success" && resp) {
if(!resp.success && resp.code == -999) {
vm.$message({
message: resp.message || vm.Common.errorMsg.generally,
type: 'error'
});
setTimeout(function() {
vm.$router.replace(vm.Common.projectName + '/user/login');
}, 2000);
} else {
app.isFunction(setting.success) && setting.success(resp);
}
}
},
error: function(xhr, type, errorThrown) {
var errorMsg = {
'timeout': '連線超時',
'error': '網路連線異常',
'abort': '網路已斷開',
'parsererror': '解析錯誤',
};
if(!setting.hideError) {
console.log((setting.url + errorMsg[type]) || 'ajax出錯了');
vm.$message({
message: errorMsg[type] || '介面出錯',
type: 'error'
});
}
app.isFunction(setting.error) && setting.error(errorMsg[type]);
},
complete: function(xhr, status, settings) {
if(showWaiting) {
app.closeMask();
}
typeof(setting.complete) == "function" && setting.complete(xhr, status, settings);
}
};
setting.beforeSend && (defaultSetting.beforeSend = setting.beforeSend);
defaultSetting.data = setting.data || {};
if(showWaiting) {
app.showMask(setting.waitingElement || '');
}
console.log('正在請求api:' + setting.url);
defaultSetting.url = setting.url;
if(_hmt) {
var category = setting.url.split('/api/')[1].split('/');
if(category.length == 2) {
_hmt.push(['_trackEvent', category[0], category[1]]);
}
}
$.ajax(defaultSetting);
},
複製程式碼