如何使用JSON检索OpenWeatherMap数据

How to retrieve OpenWeatherMap data using JSON?

本文关键字:OpenWeatherMap 数据 检索 JSON 何使用      更新时间:2023-09-26

我一直在尝试用JavaScript编写一个程序,该程序可以使用JSON从OpenWeatherMap检索天气数据。我对JSON很陌生,但我认为我理解它背后的逻辑。然而,当我点击"获取JSON"按钮时,什么都没有发生。getJSON函数中的"data.temp"可能是不正确的,但如果我理解正确,它似乎至少应该打印"Temperature"一词:HTML和JavaScript附在下面,如果有任何帮助,我们将不胜感激。

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">    </script>  
<div id = "owmData" style = "background-color:#cc0;">
     Weather data should go here.
  </div>

获取JSON

JavaScript:

$(document).ready(function() {
/* Operate when "getIt" button is clicked.*/
$("#getIt").click(function(event){      
 /* Variable storing weather information.*/
 var weatherNow="http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=******************";
 $.getJSON(weatherNow,function(data){         
                    $('#owmdata').append('<p>Temperature : ' + data.temp+ '</p>');

});
 });
 });

在请求参数中,您将"test"指定为回调函数。你可以这样构建你的请求url,而不需要对回调的引用,并直接访问数据:

http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=*************

"temp"嵌套在属性"main"中,因此您可以将其引用为data.main.temp