无法使用openweathermap API异步获取天气

时间:2016-05-06 18:12:02

标签: javascript ajax rest

我尝试使用openweathermap API检索数据。我可以让它工作,但我似乎无法异步地做到这一点。这会导致以下错误:

  

预检响应中的Access-Control-Allow-Headers不允许使用Content-Type。

形式:

  <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,我可以让它工作,但这不是我想要的方式。如果从提交按钮调用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 + "%";
}

2 个答案:

答案 0 :(得分:1)

摆脱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密钥:(

答案 1 :(得分:0)

这是CORS的一个问题。解决方法是使用JSONP。 OpenWeatherMap的API似乎是supported

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的密钥。