代码之家  ›  专栏  ›  技术社区  ›  user3390812

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

  •  1
  • user3390812  · 技术社区  · 7 年前

    标题几乎说明了问题所在。我已经在地址栏中输入了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 回复  |  直到 7 年前
        1
  •  2
  •   CertainPerformance    7 年前

    尝试指定完整路径:

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

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