我有一個評論彈出視窗,當使用 x 按鈕關閉時,它應該自行關閉,然后呼叫 XMLHttpRequest 來呼叫 Web 服務以更新一些反饋資訊。
我遇到的問題是,當單擊按鈕時,彈出視窗不會立即關閉,但似乎在等待 XMLHttpRequest 回傳 200。這是由于“EventListener”行為還是“XMLHttpRequest”?
我可能應該提到我專門通過“false”引數使 XMLHttpRequest 同步,因為當請求是異步的xmlHttp.open( "GET", URL, false );
時這似乎是必需的,例如:不運行并且需要設定下線所需的全域變數。xmlHttp.open( "GET", URL, true);
if (xmlHttp.status === 200)
我在下面添加了我的代碼。
有沒有辦法讓我的feedbackPopup()
功能關閉彈出視窗而無需等待 Web 服務 200?我需要立即關閉視窗。
對不起,如果我在某個地方犯了一個愚蠢的錯誤,還在學習。
預先感謝您的任何幫助。
//used for running closeFeedback Logic
var close = document.getElementById('closeOverlay');
close.addEventListener('click', closeFeedback);
function updateFeedback(a, b, c){
const host = window.location.host;
let URL = 'someURL${a}${b}${c}'
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", URL, false ); // false for synchronous request
xmlHttp.send( null );
if (xmlHttp.status === 200){
// this is not set for future use if line 14 is set to true
SomeGlobal = b;
}else{
console.log("xmlHttp.status","",xmlHttp.status)
}
}
//this is used for both opening and closing the popup which is why the conditional operator is used
function feedbackPopup() {
el = document.getElementById("feedback");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
//should close feedback and call web service function
function closeFeedback(){
//ISSUE : this closeFeedbackWindow should close the window before updateFeedback runs and should not wait for updateFeedback to retunr 200???
feedbackPopup();
updateFeedback(a, b, c);
...
//More logic here which uses the SomeGlobal variable set in updateFeedback
}
uj5u.com熱心網友回復:
正如JaromandaX 所說,問題在于您正在發出同步ajax 請求。這會在網路操作運行時鎖定瀏覽器的 UI(至少是那個選項卡,在某些瀏覽器中比這更糟)。讓請求默認為異步。(同步請求甚至可能有一天會停止作業。)
如果第 14 行設定為 true,則不會設定為將來使用
那只是因為您沒有正確處理請求。要處理異步請求,請使用onload
and onerror
(或onreadystatechange
更詳細);更多在MDN 的檔案中。而且由于您在呼叫 后有進一步的邏輯updateFeedback
,因此您需要(如果我們以老式方式執行此操作)為其添加回呼:
function updateFeedback(a, b, c, callback) {
const host = window.location.host;
let URL = 'someURL${a}${b}${c}'
var xmlHttp = new XMLHttpRequest();
xmlHttp.onload = () => {
SomeGlobal = b;
callback(true); // Worked
};
xmlHttp.onerror = () => {
console.log("xmlHttp.status", "", xmlHttp.status)
callback(false); // Didn't work
};
xmlHttp.open("GET", URL);
xmlHttp.send(null);
}
對它的呼叫變為:
updateFeedback(a, b, c, (success) => {
//More logic here which uses the SomeGlobal variable set in updateFeedback
});
或者更好的是,使用fetch
現代標準替換XMLHttpResponse
,并使updateFeedback
return 成為一個承諾:
function updateFeedback(a, b, c) {
const host = window.location.host;
let URL = 'someURL${a}${b}${c}'
fetch(URL)
.then((response) => {
if (response.ok) {
SomeGlobal = b;
} else {
throw new Error(`HTTP error, status = ${response.status}`);
}
})
.error((error) => {
console.log(error.message ?? error);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508479.html
標籤:javascript 异步 xmlhttp请求 添加事件监听器