【问题标题】:How to show some json objects如何显示一些 json 对象
【发布时间】:2021-06-24 23:47:52
【问题描述】:

我正在尝试使用 ajax 获取 JSON 文件并将其显示在 HTML div 中,但只是其中的一部分,而不是全部。

这里是ajax

    $(function () {
  $.ajax({
  'url': 'http://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
  'type': 'GET',
  'dataType': 'json',
  'success': function(response) {
  }
});
});

我正在尝试仅放置一些对象,例如 HTML div 中的温度

    <!DOCTYPE html>
<html lang="is" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="js/main.js"></script>
  </head>
  <body>
    <div id="result">
      <p>i want the result here</p>
    </div>
  </body>
</html>

有人知道这些吗?

【问题讨论】:

标签: javascript html jquery json ajax


【解决方案1】:

你可以从这里开始,我展示了整个对象但是你需要根据你的需要来解析数据

$(function() {
  $.ajax({
    'url': 'http://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
    'type': 'GET',
    'dataType': 'json',
    'success': function(response) {
      displayData(response);
    }
  });
});

function displayData(data) {
  document.getElementById("result").innerHTML  = JSON.stringify(data, null, 4);
  //parse the data and display only the fields that you need and display with innerHTML
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div>
    <p id="result">i want the result here</p>
  </div>
</body>

【讨论】:

    【解决方案2】:

    考虑下面的代码。

    $(function() {
      function showHtmlData(obj) {
        var html = "";
        $.each(obj, function(key, value) {
          html += key + ": " + value + "<br />";
        });
        return html;
      }
    
      function showJson(json) {
        $("#result p").html(showHtmlData(json));
      }
      $.ajax({
        'url': 'https://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
        'type': 'GET',
        'dataType': 'json',
        'success': function(response) {
          showJson(response.results[0]);
        }
      });
    });
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    
    <div id="result">
      <p></p>
    </div>

    这将获取 JSON 数据,将其转换为字符串,并将其添加到 &lt;p&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2015-10-27
      相关资源
      最近更新 更多