我的 ajax 請求非常慢,所以我的 stats 陣列在我第二次想要訪問它時沒有得到更新。似乎在處理完所有代碼后才執行 ajax 請求。有沒有辦法讓我在所有其他代碼之前等待 ajax 請求執行?
console.log(stats);
fetchREST(false, (url selectedID "/solve"), (parseInt(button.id) 1), function(data){
if (data.success) {
console.log("richtig");
stats.right ;
} else {
console.log("falsch");
stats.wrong ;
}
});
console.log(stats);
function fetchREST(isGET, path, answer, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
let email = "*";
let pw = "*";
if(isGET) {
// not needed
} else {
let solutionArray = '[' answer ']';
console.log(solutionArray);
httpRequest.open('POST', path, true);
httpRequest.setRequestHeader("Content-Type", "application/json");
httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*");
httpRequest.setRequestHeader("Access-Control-Allow-Headers", "*");
httpRequest.setRequestHeader("Authorization", "Basic " window.btoa(email ":" pw));
httpRequest.send(solutionArray);
}
}
編輯 我通過改變來修復它
httpRequest.open('POST', path, true);
至
httpRequest.open('POST', path, false);
現在 async 設定為 false 并且 send 方法一直等到收到回應。
uj5u.com熱心網友回復:
我通過更改自己修復了它
httpRequest.open('POST', path, true);
至
httpRequest.open('POST', path, false);
現在 async 設定為 false 并且 send 方法一直等到收到回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485138.html
標籤:javascript 阿贾克斯 休息
