javascript - OpenWeather API - 提取 JSON 数据

标签 javascript html json api

我正在编写一些 JavaScript 以从包含名称、经度、纬度和 openweather API 调用的 JSON 中提取信息。我需要的是将 API 信息从 API 调用中获取到 HTML 页面中,以便您可以获取每个信息的天气预报。我让这两个元素分开工作,但不知道如何让它们一起工作。

请帮忙? :-)

来自 d.weather 的示例 API 天气

 api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric

用于提取 openweather JSON 数据的 HTML 页面

<html>
<head>
<title>Weather</title>
    <meta charset="utf-8">

    <script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
    <script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>

<script>
function getWeather(callback) {
    var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
    $.ajax({
      dataType: "jsonp",
      url: weather,
      success: callback
    });
}

// get data:
getWeather(function (data) {
    console.log('weather data received');
    console.log(data.list[0].weather[0].description); 
    console.log(data.list[0].weather[0].main);  
});

getWeather(function (data) {
    document.write('weather data received');
    document.write('<br>');
    document.write(data.list[0].weather[0].description);
    document.write('<br>');
    document.write(data.list[0].weather[0].main);
    document.write('<br>');
    document.write(data.list[0].main.temp);
    document.write('<br>');
    document.write(data.list[0].main[0].dt_txt);
    document.write('<br>');
});
</script>
</body>
</html>

用于拉取 JSON 数据的 Html 页面

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> 
<!-- Javascript -->

<script type="text/javascript">
function loadUrl(newLocation){
    window.location = newLocation;
    return false;
}
</script>

<script type="text/javascript">
$(document).ready(function (){
    $("#btn382").click(function(){       
        /* set no cache */
        $.ajaxSetup({ cache: false });

        $.getJSON("weather.json", function(data){
            var html = [];

            /* loop through array */
            $.each(data, function(index, d){           
                html.push("Team : ", d.Teams, ", ",
                          "Long : ", d.Long, ", ",
                          "Lat : ", d.Lat, ", ",
              "Weather : ", d.Weather, "<br>");        
            });


            $("#div381").html(html.join('')).css("background-color", "orange");
        }).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
            /* alert(jqXHR.responseText) */
            alert("error occurred!");
        });
    });
});
</script>

<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">   
    <div>Football weather</div>
    <div id="div381"></div>
    <button id="btn382" type="button">Team location</button>
</div>

天气.json

{
    "Teams":"Wycombe Wanderers",
    "Long":-0.800299,
    "Lat":51.6306,
    "Weather":"  api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
  },
  {
    "Teams":"Livingston",
    "Long":-3.52207,
    "Lat":55.8864,
    "Weather":"  api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
  },
  {
    "Teams":"Brighton and Hove Albion",
    "Long":-0.08014,
    "Lat":50.8609,
    "Weather":"  api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
  },

最佳答案

我有一些基础知识可以帮助你。它是您的两个页面的混搭。

首先,我修改了您的 getWeather 函数以调用天气而不是预报。它接受一个 city 参数,并在调用回调之前将该参数附加到数据。

function getWeather(city, callback) {
  var url = 'http://api.openweathermap.org/data/2.5/weather';
  $.ajax({
    dataType: "jsonp",
    url: url,
    jsonCallback: 'jsonp',
    data: { q: city },
    cache: false,
    success: function (data) {
        data.city = city;
        callback(data);
    }
  });
}

在这里,我以 JS 对象的形式代替您的球队 JSON,以阿森纳和利物浦及其相应的城市作为数据。该函数遍历该对象,提取城市名称并将其传递给 getWeather。返回数据并将其附加到 div。

$(document).ready(function () {

  $("#btn382").click(function () {

    var teams = {
      arsenal: { city: 'london' },
      liverpool: { city: 'liverpool' }
    };

    for (var team in teams) {
      var city = teams[team].city;
      getWeather(city, function(data) {
        var html = [];
        html.push('<div>')
        html.push('City: ', data.city, ', ');
        html.push('Lat: ', data.coord.lat, ', ');
        html.push('Lon: ', data.coord.lon, ', ');
        html.push('Weather: ', data.weather[0].description);
        html.push('</div>')
        $("#div381").append(html.join('')).css("background-color", "orange");
      });
    }

  });
});

希望这会给你一些关于如何处理这个项目的想法。

See it working here.

关于javascript - OpenWeather API - 提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18918195/

相关文章:

html - 构建与移动设备兼容的单个页面 - 从哪里开始?

html - Bootstrap : Keeping the input fields inline in a fluid span

python - Flask request.get_json() 引发 BadRequest

javascript - Backbone Collection 获取抛出 id 错误

html - 带有静态 HTML 的通用页眉/页脚

java - 如何使用JAVA查询标点符号敏感术语的Marklogic?

javascript - 使用 Javascript 为内容设置样式

javascript - 将评论中的 URL 解析为链接

javascript - 图像仅在 Canvas 上选择时出现 Fabric JS

javascript - 如何更新发散堆积条形图d3js中的数据