无法使用开放天气图 API 异步获取天气

Can't get weather asynchronously using openweathermap API

本文关键字:异步 API 获取 天气图      更新时间:2023-09-26

我正在尝试使用openweathermap API检索数据。 我可以让它工作,但我似乎不能异步地做。 这会导致以下错误:

印前检查响应中的访问控制允许标头不允许内容类型。

形式:

  <label>Zipcode: </label>
  <form>
       <input type="text" id="locationField" name="locationField">
       <input type="submit" id="weatherSubmit" value="Get Weather">
  </form>
  <div>
      <br>
      <label>Location:</label>
      <div id="location"></div>
      <br>
      <label>Temperature:</label>
      <div id="temperature"></div>
      <br>
      <label>Humidity</label>
      <div id="humidity"></div>
  </div>

脚本:

document.getElementById('weatherSubmit').addEventListener('click', function(event) {
    var zipcode = document.getElementById('locationField').value;
    var req = new XMLHttpRequest();
    var payload = {location: null, temperature:null, humidity:null};
    req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + zipcode + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.addEventListener('load',function(){
      if(req.status >= 200 && req.status < 400){
          var response = JSON.parse(req.responseText);
          document.getElementById('location').textContent = response.name;
          document.getElementById('temperature').textContent = response.main.temp;
          document.getElementById('humidity').textContent = response.main.humidity;
      } else {
        console.log("Error in network request: " + request.statusText);
      }});
    req.send(JSON.stringify(payload));
    event.preventDefault();
});

如果我不使用 AJAX,我可以让它工作,但这不是我想要的方式。 如果从提交按钮调用 onclick 并传入邮政编码值foo(),则以下代码有效。

function foo(value) {
    var req = new XMLHttpRequest();
    req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", false);
    req.send(null);
    var response = JSON.parse(req.responseText);
    document.getElementById('location').textContent = response.name;
    var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
    document.getElementById('temperature').textContent = f + "f";
    document.getElementById('humidity').textContent = response.main.humidity + "%";
}

摆脱setRequestHeader

var req = new XMLHttpRequest();
    var payload = {location: null, temperature:null, humidity:null};
    req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=02143,us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
    //req.setRequestHeader('Content-Type', 'application/json');
    req.addEventListener('load',function(){
      if(req.status >= 200 && req.status < 400){
          var response = JSON.parse(req.responseText);
          console.log(response);
          //document.getElementById('location').textContent = response.name;
          //document.getElementById('temperature').textContent = response.main.temp;
          //document.getElementById('humidity').textContent = response.main.humidity;
      } else {
        console.log("Error in network request: " + request.statusText);
      }});
    req.send(null);

效果很好!

顺便说一句。更改您的 API 密钥:(

这是

CORS的问题。解决方法是使用 JSONP。它似乎得到了OpenWeatherMap的API的支持。

function foo(value) {
  window.weatherCallback = function(response) {
    document.getElementById('location').textContent = response.name;
    var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
    document.getElementById('temperature').textContent = f + "f";
    document.getElementById('humidity').textContent = response.main.humidity
    delete window.weatherCallback; // delete the property
  };
  var script = document.createElement('script');
  script.src = '//api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1&callback=weatherCallback';
  document.head.appendChild(script);
}

无法测试它,因为我没有 API 的密钥。