【发布时间】:2017-10-30 00:06:16
【问题描述】:
我正在使用 JavaScipt 制作一个简单的天气应用程序。我的目标是当用户输入一个位置而天气提供者没有该位置时,输入框会抖动(这就是 loadWeatherError() 所做的)。下面的代码运行 else 语句两次,然后运行 if 代码。这意味着 loadWeatherError() 函数正在运行两次,即使位置有效,输入框也会抖动。因此,当我运行它时,我收到两次错误 2 警报,然后收到一次错误 1 警报。有没有办法只让 loadWeatherError() 函数只运行一次,并且只在天气提供者没有返回正确数据的情况下运行?
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 视为错误。 developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
-
除非你的问题是你的内部 OK 检查不使用 {} 以便其他与之配对。
-
我不认为状态 0-3 是错误的。我相信发生的事情是每次状态更改时函数都会运行,并且由于它不在状态 4 时运行 else 代码。然后它到达下一个状态,else 代码再次运行,直到它到达状态 4。但是,我看不出基于此代码会如何发生。
标签: javascript weather-api yahoo-weather-api