使用GET XHR脚本时未捕获的TypeError错误。无法阅读财产' abort'未定义的

时间:2016-04-25 22:43:23

标签: javascript xmlhttprequest

下面的脚本应该发送XMLHttpRequest,但是当它运行时会在控制台中抛出Uncaught TypeError: Cannot read property 'abort' of undefined。这是一个家庭作业,我有三重检查,以确保这是他们告诉我运行的代码...我找不到任何错误。但无论如何,我只想让它发挥作用。

我能说的最多的是变量' httpRequest'被注册为未定义...也许它被分配给它的功能?我迷路了,不知道如何解决它。

// global variables
var selectedCity = "Tucson, AZ";
var httpRequest = false;
var weatherReport;

function getRequestObject() { // Possible function responsible for error?
  try {
    httpRequest = new XMLHttpRequest();
  }
  catch (requestError) {
    document.querySelector("p.error").innerHTML = "Forecast not supported by your browser.";
    document.querySelector("p.error").style.display = "block";
    return false;
  }
}

function getWeather(evt) {
   var latitude;
   var longitude;
   if (evt.type !== "load") {
      if (evt.target) {
         selectedCity = evt.target.innerHTML;
      } else if (evt.srcElement) {
         selectedCity = evt.srcElement.innerHTML;
      }
   }
   if (selectedCity === "Tucson, AZ") {
      latitude = 37.7577;
      longitude = -122.4376;
   } else if (selectedCity === "Chicago, IL") {
      latitude = 41.8337329;
      longitude = -87.7321555;
   } else if (selectedCity === "Montreal, QC") {
      latitude = 45.5601062;
      longitude = -73.7120832;
   }
   if (!httpRequest) {
     httpRequest = getRequestObject();
   }
   httpRequest.abort(); // Where the error is thrown...
   httpRequest.open("get","solar.php?" + "lat=" + latitude + "&lng=" + longitude, true);
   httpRequest.send(null);
   httpRequest.onreadystatechange = fillWeather;
}

function fillWeather() {
  if(httpRequest.readyState === 4 && httpRequest.status === 200) {
    weatherReport = JSON.parse(httpRequest.responseText);
  }
}

var locations = document.querySelectorAll("section ul li");
for (var i = 0; i < locations.length; i++) {
   if (locations[i].addEventListener) {
      locations[i].addEventListener("click", getWeather, false);
   } else if (locations[i].attachEvent) {
      locations[i].attachEvent("onclick", getWeather);
   }
}
if (window.addEventListener) {
   window.addEventListener("load", getWeather, false);
} else if (window.attachEvent) {
   window.attachEvent("onload", getWeather);
}

1 个答案:

答案 0 :(得分:0)

您忘记了return httpRequest中的getRequestObject(),因此httpRequest = getRequestObject()将其设置为未定义。