【问题标题】:Grabbing Values from a JSON API Responce, putting them into webpage从 JSON API 响应中获取值,将它们放入网页
【发布时间】:2016-01-29 03:29:34
【问题描述】:

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

据我所知,javascript 正在获取温度并将其设置为 var。我很困惑为什么我不能使用 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>

【问题讨论】:

  • 脚本中有语法问题...在脚本末尾缺少})
  • $('#temp').html(temp); 在成功处理程序中显示p 中的值
  • 非常感谢,帮了大忙。

标签: javascript jquery html json api


【解决方案1】:

@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>

【讨论】:

  • 非常感谢您的帮助。我现在可以愉快地结束这一天了!我很高兴看到我不是超级傻逼
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
相关资源
最近更新 更多