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);
},
复制代码