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

标签 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)

    }
  }
})();

最佳答案

尝试指定完整路径:

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

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

关于javascript - XMLHTTPRequest 请求打开天气返回状态 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49620587/

相关文章:

javascript - 通过函数添加到对象

javascript - 将 Unix 时间戳转换为工作日

swift - Alamofire 将应用程序 API 放在 url 的开头而不是结尾

javascript - 在循环语句之外继续(在 some() 中)

javascript - Magento 响应主题 : Menu not showing up between 980 and 740 widths

javascript - 尝试从公共(public) API 解析 JSON 响应数据

javascript - 如何分解 openweathermap API 返回的这个长字符串?

Web Worker 中的 Ajax 限制

javascript - react native WebView : Load html and js from assets folder

javascript - Jest 中的 XMLHttpRequest 测试