// 先假裝有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.
show
Loading
(
loadingTxt
,
time
)
let
starttime =
Number(
new
Date());
$.
ajax({
url,
type:
method.
toUpperCase(),
dataType,
xhrFields: {
withCredentials:
true
},
crossDomain:
true,
data,
headers: {
...
headers
}
})
.
done(
res
=> {
util.hide
Loading();
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.hideL
oading();
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))
})
})
}