2017-05-29 65 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

这不起作用。 –