jquery ajax 設置請求頭header 參數


// 先假裝有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))
})

})
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM