為什么 If 和 else 條件都適用于 JavaScript。if (xhr.readyState == 4 && xhr.status == 200)
我正在開發 php MVC 專案。
我在后臺 JavaScript 中創建了一個組態檔編輯頁面,If并且Else兩個代碼都在執行。組態檔編輯成功,但其他代碼作業,并顯示錯誤“抱歉,此內容現在不可用”。
為什么這個else條件有效?
- 相同此代碼在登錄和注冊頁面中作業。
- 保存在本地檔案中并運行比它作業:-
幫我!謝謝!!
uj5u.com熱心網友回復:
該
readystatechange事件會觸發多次。Value State Description 0 UNSENT Client has been created. open() not called yet. 1 OPENED open() has been called. 2 HEADERS_RECEIVED send() has been called, and headers and status are available. 3 LOADING Downloading; responseText holds partial data. 4 DONE The operation is complete.您的
if (xhr.readyState == 4 && xhr.status == 200) {如果請求成功,分支只會在請求結束時進入。但早些時候,當請求還在進行時,會發生其他狀態變化,
else進入分支。相反,僅當 readyState 為 4 時才執行任何操作 - 當它為 4 時,您可以決議回應,或填充
#Profile_Edit_Msg以表示存在問題。其他改進:
- 將其保存
Profile_Edit_Msg在一個變數中,而不是一遍又一遍地重復選擇它 - 使用嚴格相等,而不是草率相等
- 將文本分配給元素時使用
.textContent- 僅.innerHTML在插入 HTML 標記時使用 - JSON 是一種特殊格式的字串,可以反序列化為物件或其他值。
JSON.parse不回傳 JSON -使用JSON.parseJSON 格式的字串呼叫并回傳一個物件。將您的變數稱為其他名稱。json denger看起來拼寫錯誤 - 你的意思是danger什么?(錯別字是編程中的常見問題 - 最好早點修復它們)
xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } const profile = document.querySelector("#Profile_Edit_Msg"); if (xhr.status === 200) { const result = JSON.parse(xhr.responseText); if (result.Status === "Ok") { window.location.href = "Profile"; } else { profile.classList.remove("active_success"); profile.classList.add("active_denger"); profile.innerHTML = json.Message; } } else { profile.classList.add("active_denger"); profile.textContent = "Sorry, this content isn't available right now"; } };您還可以考慮使用fetch API而不是 XMLHttpRequest -
fetch使用起來更好一些,并且在所有現代瀏覽器中都得到了支持。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490935.html標籤:javascript json if 语句
- 將其保存
