从 JSON API 响应中获取值,将它们放入网页中

Grabbing Values from a JSON API Responce, putting them into webpage

本文关键字:网页 API JSON 响应 获取      更新时间:2023-09-26

今天我有一个问题,在你们其他人看来似乎很简单。我现在刚刚学习如何使用 API/JSON,我有点困惑。我试图简单地从这个 openweathermap.org API 响应中获取温度并将其显示在 html 标签中。

据我所知,javascript正在抓取温度并将其设置为变量。我很困惑为什么我不能使用 id=" 在标签内设置文本。下面的代码是我到目前为止拥有的代码。我感谢你的时间。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
    dataType: 'jsonp',
    success: function(weather){
    var temp = weather.main.temp;
}
}); 
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>

@ArunPJohny已经发现了错误:1)缺少})和2)使用$('#temp')获取HTML元素。此外,您不需要声明weather因为它被声明为参数。

$(document).ready(function() {
  $.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
    dataType: 'jsonp',
    success: function(weather) {
      $('#temp').text(weather.main.temp);
    }
  });
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>