XMLHTTPRequest请求打开天气返回状态0

时间:2018-04-03 00:31:25

标签: javascript xmlhttprequest openweathermap

标题几乎说明了这个问题。我已将URL输入到我的地址栏中,它又回来了。我觉得它是一种愚蠢的东西,我只能看到它,因为我已经盯着它看了一段时间,但这里是代码。

(function() {
  var httpRequest;
  document.getElementById("weatherButton").addEventListener('click', makeRequest);
  function makeRequest() {
    httpRequest = new XMLHttpRequest();
    if (!httpRequest) {
      alert('Cannot create XMLHTTP instance!');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
    httpRequest.open("GET", "api.openweathermap.org/data/2.5/weather?zip=94040&APPID=xxxxxxxxx&mode=json");
    httpRequest.send();
  }
  function alertContents() {
    if (httpRequest.readyState != 4) {
      return;
    }
    if (httpRequest.status == 200) {
      alert(httpRequest.responseXML);
    }
    if (httpRequest.status != 200) {
      alert(httpRequest.status + ": " + httpRequest.statusText_)
      alert(httpRequest.readyState)

    }
  }
})();

1 个答案:

答案 0 :(得分:2)

尝试指定完整路径:

httpRequest.open("GET", "https://api.openweathermap.org/data/2.5/weather?zip=94040&APPID=xxxxxxxxx&mode=json");

否则,它会查找[yourdomain]/api.openweathermap.org/...