Weather API无效

时间:2018-04-14 07:00:24

标签: javascript

为什么我没有从天气api获取任何数据我正在尝试更新html标签以显示温度请帮助



$(document).ready(function() {
  var loc = [];
  console.log(loc);
  $.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
    loc = response.loc.split(",");
     

    document.getElementById("Location").innerHTML =
      response.city + "," + response.country;
  });
  $.getJSON(
    "https://fcc-weather-api.glitch.me/api/current?lat=" +
      loc[0] +
      "&lon=" +
      loc[1],
    function(data) {
      console.log(data);
      document.getElementById("Temperature").innerHTML = data.main.temp;
    }
  );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

这是因为当您拨打第二个请求时,第一个请求尚未完成,因此lat long值为undefined

你需要把你的第二个请求放在第一个请求内:

$(document).ready(function() {
  var loc = [];
  $.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
    loc = response.loc.split(",");
    console.log(Number(loc[0]));
     

    document.getElementById("Location").innerHTML =
      response.city + "," + response.country;
      
      $.getJSON(
    "https://fcc-weather-api.glitch.me/api/current?lat=" +
      loc[0] +
      "&lon=" +
      loc[1],
      function(data) {
      console.log(data);
      document.getElementById("Temperature").innerHTML = data.main.temp;
    }
  );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Location"></div>
<div id="Temperature"></div>