各位大佬好!我在用promise封裝ajax請求時,用了mock資料測驗,采用的easy mock API管理工具,用測驗介面鏈接回傳的資料對了,但是無法呼叫回傳的資料,在ajax請求程序中 顯示的readyState值是2 但是點開資料物件中顯示的卻是4, 這是怎么回事?
// 請求路徑物件
var root = {
method: 'GET',
url: 'https://easy-mock.com/mock/5faa09f7234c9b0d8babecde/example/mock',
};
// 封裝請求方法
function getInfo(requestObj) {
return new Promise((resolve, reject) => {
var xhr = null
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open(requestObj.method, requestObj.url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status>=200&&xhr.status<=400) {
resolve(this.response);
} else {
reject(this.status);
}
} else {
reject(this);
}
}
xhr.send();
})
}
//執行請求
getInfo(root).then((res) => {
console.log(res)
}).catch((e) => {
//請求失敗報錯
console.log(e)
});



uj5u.com熱心網友回復:
xhr.onreadystatechange本身就是會被連續觸發的,分別對著的readyState幾種狀態,你如果readyState!=4就reject,那你這注定了是一直在reject到catch,永遠到不了resolve,然后讓then處理
//這樣你就知道它的變化了,它最終就是要到4的
xhr.onreadystatechange = function() {
console.log('readystatechange:');
console.log(this.readyState);
console.log('-----------------------');
}
最簡單的就是
if(xhr.readyState === 4) {
if(xhr.status == 200) {
resolve(this.response);
} else {
reject(this.status);
}
}
然后就是你說的readyState變成4了,這里對你錯誤的代碼不動,只是告訴你為什么發生
if (xhr.readyState === 4) {
if (xhr.status>=200&&xhr.status<=400) {
resolve(this.response);
} else {
reject(this.status);
}
} else {
/**
* 因為你reject的this是一個物件,它是參考型別,所以,它會在后續readystatechange中持續發生變化
* 你問題中的readyState值變成4,就是它最后一次觸發readystatechange后最新的值
*/
//reject(this);
/**
* 你如果深度拷貝,切斷它的參考關系,你說的后面看到值是4的情況就不會發生了。
* 我這里用的是jQuery的extend方法實作的深度拷貝
*
* 或者你直接像下面這樣,因為this.readyState是值型別,你直接reject,那它就是當時的值
* reject(this.readyState);
*/
reject($.extend({},this));
}
uj5u.com熱心網友回復:
嗯解決了,忽略了是從0-4的程序了 感謝講解!轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/211616.html
標籤:JavaScript
