【问题标题】:My xhr.onreadystatechange function is running the else code twice before running the if code我的 xhr.onreadystatechange 函数在运行 if 代码之前运行 else 代码两次
【发布时间】: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


【解决方案1】:

发生的情况是您的状态正在发生变化,但它不等于 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.");
    }
  }
};

【讨论】:

  • 但是如果没有检索到天气数据或用户输入了错误的位置,我将不会收到错误消息。
  • 您遇到了什么问题?
  • 你可以去掉第二个
猜你喜欢
  • 2015-05-20
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多