// 先假装有loading组件(util.hideLoading, util.showLoading),util.toast组件, time:表示loading时间
let ajax = (url, data = {}, params = {
showLoading: true,
showError: false,
method: 'GET', // 默认是GET,POST
dataType: 'json',
loadingTxt: '加载中...',
headers: {}
}) => {
return new Promise((resolve, reject) => {
let { method, showLoading = true, showError, loadingTxt, dataType, headers = {} } = params
if (headers['Content-Type'].indexOf('application/json') > -1) {
if (method.toUpperCase() == 'POST') {
data = JSON.stringify(data)
}
}
showLoading && util.showLoading(loadingTxt, time)
let starttime = Number(new Date());
$.ajax({
url,
type: method.toUpperCase(),
dataType,
xhrFields: {
withCredentials: true
},
crossDomain: true,
data,
headers: {
...headers
}
})
.done(res => {
util.hideLoading();
let {
code,
} = res;
if (res.returnCode == 200 || res.isSuccess || res.successful) {
resolve(res.result || res.value || res.data); // 看后端怎么包装返回数据
} else {
showError && util.toast(res.message || res.returnMsg);
reject(res);
}
})
.fail(res => {
showLoading && util.hideLoading();
reject(res && res.data);
})
.always(res => {
console.log('-'.repeat(51))
console.log("request data:", { url, data });
console.log("request params:", params);
console.log('response data', res);
console.log('excute time: ', (Number(new Date()) - starttime) + 'ms');
console.log('-'.repeat(51))
})
})
}