我正在用JavaScipt製作一個簡單的天氣應用程序。我的目標是當用戶鍵入某個位置並且天氣提供者沒有該位置,然後輸入框抖動(這是loadWeatherError()的作用)。下面的代碼運行else語句兩次,然後運行if代碼。這意味着loadWeatherError()函數正在運行兩次,即使該位置有效,輸入框也會抖動。所以當我運行它時,我得到錯誤2警報兩次,然後錯誤1警告一次。有沒有一種方法只會使loadWeatherError()函數只運行一次,並且只在天氣提供程序沒有返回正確的數據時才運行? 我的xhr.onreadystatechange函數在運行if代碼之前運行else代碼
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK)
alert("Error 1");
var data = JSON.parse(xhr.responseText);
if (data.response) { //deal with wunderground api
} else { //deal with Yahoo api
}
} else {
alert("Error 2");
loadWeatherError();
options.error("There is a problem receiving the latest weather. Try again.");
}
};
您是否在控制檯上記錄了readyState以查看其值是多少?我有點困惑,爲什麼你把狀態0-3視爲錯誤。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState – Taplar
除非您的問題與您的內部OK檢查不使用{},否則與其配對。 – Taplar
我不認爲狀態0-3是錯誤。我相信,每次狀態改變函數運行時都會發生什麼,並且因爲它不處於狀態4,所以其他代碼運行。然後它到達下一個狀態,其他代碼再次運行,直到達到狀態4.但是,我不明白基於此代碼會發生這種情況。 –