使用JSON拉出Weather API数据并附加到li?

时间:2015-04-22 22:51:01

标签: jquery json appendto weather-api openweathermap

我无法弄清楚如何提取OpenWeatherMap API数据并将其附加到我的html中的相应li中。感谢您的帮助,我现在被困在以下代码中:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Project 21</title>
  <style>
    html {margin:2em; font-size:2em; font-family:Helvetica, Arial, sans-serif;}
    h1 {margin:0 0 0.2em; color:#369;}
    img {float:left; margin-right:1em;}
    ul {float:left; margin:0; padding:0; list-style:none;}
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
  <section>
    <h1>Current Weather for </h1>
    <div class="img" id="data-img"></div>
    <ul>
      <li><b>Conditions:</b> <span id="data-current"></span></li>
      <li><b>Temperature:</b> <span id="data-temp"></span>&deg;</li>
      <li><b>Humidity:</b> <span id="data-humidity"></span>%</li>
      <li><b>Wind Speed:</b> <span id="data-wind"></span>mph</li>
    </ul>
  </section>
  <script>
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?callback=?',
  { 'zip': '46556,us', 'units':'imperial' },
    function(data){
      console.log(data);
  })
  .fail(function(jqxhr, textStatus, error) {
    console.log("Request Failed"+ textStatus + "," + error);
  });



  </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您应该搜索JQuery选择器以操作标记属性或文本。但是,这是你的答案:

$.getJSON('http://api.openweathermap.org/data/2.5/weather?callback=?', { 'zip': '46556,us', 'units': 'imperial' }, function(data){ 
            console.log(data);
            $("#data-current").text(data.weather[0].description);
            $("#data-temp").text(data.main.temp);
            $("#data-humidity").text(data.main.humidity);
            $("#data-wind").text(data.wind.speed);
        })
        .fail(function(jqxhr, textStatus, error) {
        console.log("Request Failed" + textStatus + "," + error);
        });

要使用与openWeather相关的其他数据,请检查您在控制台中显示的数据。