2017-05-29 61 views
0

我正在用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."); 
 
    } 
 

 
};

+0

您是否在控制檯上記錄了readyState以查看其值是多少?我有點困惑,爲什麼你把狀態0-3視爲錯誤。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState – Taplar

+0

除非您的問題與您的內部OK檢查不使用{},否則與其配對。 – Taplar

+0

我不認爲狀態0-3是錯誤。我相信,每次狀態改變函數運行時都會發生什麼,並且因爲它不處於狀態4,所以其他代碼運行。然後它到達下一個狀態,其他代碼再次運行,直到達到狀態4.但是,我不明白基於此代碼會發生這種情況。 –

回答

0

正在發生的事情是你的狀態正在改變,但它不等於4.你必須去通過每個就緒狀態,以達到DONE值。每次狀態更改時,您的代碼都在運行,這是導致錯誤的原因。如果狀態不正確,請刪除輸出錯誤的代碼:

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"); 
    } else { 
     alert("Error 2"); 
     loadWeatherError(); 
     options.error("There is a problem receiving the latest weather. Try again."); 
    } 
    var data = JSON.parse(xhr.responseText); 
    if (data.response) { //deal with wunderground api 

    } else { //deal with Yahoo api 
     alert("Error 2"); 
     loadWeatherError(); 
     options.error("There is a problem receiving the latest weather. Try again."); 
    } 
    } 
}; 
+0

但是,如果未檢索到天氣數據或者用戶輸入了錯誤的位置,我將不會收到錯誤消息。 –

+0

在這裏,我會編輯它! 1秒 –

+0

這不起作用。 –