javascript - 在 HTML 中使用 JSON 脚本并显示数据

标签 javascript jquery html json

这是 JSON 的链接。 http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

此 JSON 文件提供有关天气的数据

我想将上面链接给出的数据显示到我的 HTML 文件中。我是第一次使用 JSON。因此,我需要帮助将此 JSON 文件链接到我的 HTML 文档中。

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>

<body>

<div class="wrapper">
<span id="temp"></span>
<span id="high"></span>
<span id="low"></span>
<span id="windspeed"></span>
<span id="description"></span>
<span id="city"></span>
<span id="iconorimage"></span>
<span id="time"></span>
<span id="any thing else"></span>
</div>
</body>
</html>

我可以,如果我能只显示温度、城市、天气图标[雨、晴]、有关天气、高/低、风速和时间的文字描述。

最佳答案

您可以像在 JavaScript 中访问对象属性一样访问 json 对象。

$.ajax({
  dataType: "json",
  url:"//api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json",
  success: function(data){
    $('#city').text("City : " + data["current_observation"]["display_location"]["city"]);
    $('#high').text("High : " + "");//Insert data for high here
    $('#low').text("Low : " +""); //Insert data for low here
    $('#temp').text("Tempearature : " + data["current_observation"]["temperature_string"]);
    $('#description').text("Description : " + data["current_observation"]["icon"]);
    $('<img />').attr('src',data["current_observation"]["icon_url"]).appendTo($("#iconorimage"));
  $('#windspeed').text('WindSpeed : ' + data["current_observation"]["wind_kph"]);
  $('#time').text('Time : ' + data["current_observation"]["observation_time"]);
  }
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<span id="temp"></span><br/>
<span id="high"></span><br/>
<span id="low"></span><br/>
<span id="windspeed"></span><br/>
<span id="description"></span><br/>
<span id="city"></span><br/>
<span id="iconorimage"></span><br/>
<span id="time"></span><br/>
<span id="any thing else"></span><br/>
</div>
</body>
</html>

关于javascript - 在 HTML 中使用 JSON 脚本并显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44964205/

相关文章:

javascript - 为什么 z-index 没有像我期望的那样工作?

javascript - 如何将选定的 HTML 转换为 Json?

javascript - array.splice() 给出错误 TypeError : arr. splice 不是函数(…)

javascript - 关闭 Bootstrap 模式

javascript - 在 Highcharts 中,将小选区放大到边缘,当 Zoomtype = x 时会同时缩放 x 和 y

html - 导航栏按钮在 Chrome 和 IE 上移动

html - CSS 垂直导航菜单下拉菜单在 IE11 中不起作用

java - 如何将前一个jsp页面的值检索到结果页面?

javascript - 如何使用jquery清除和设置nopcommerce中的文本框、复选框和下拉列表

javascript - 如何将嵌套的 json 数据绑定(bind)到 angularjs 下拉列表中?