【问题标题】:How to Display Api Data in HTML?如何在 HTML 中显示 API 数据?
【发布时间】:2021-06-28 03:12:05
【问题描述】:
<script>
     function fetchdata() {
     $.get("http://10.10.35.138:5000/data", function (data) { //The link of this line is my api link
                $("#visitor").html('Visitor Count : ' + data.people);
                $("#time").html('Time : ' + data.time);
            });
        }
</script>

****HTML PART****
<div class="details">
<p id="visitor">Person Count:</p>
<p id="time">Time:</p>`enter code here`
</div>

我的 Api 数据由计数和时间两部分组成。我在上面提到了两段:我想在第一段标签中显示计数。我想显示时间是另一段。我尝试了更多时间,但 API 数据不会出现段落标签。请帮帮我

【问题讨论】:

标签: javascript html jquery api web


【解决方案1】:

您需要一个循环来对从 api 提供程序获取的数据进行迭代

$.each(data, function( index, value ) {
});

对于每次迭代,我们需要将值添加到 html:

$("#details").append('<p id="visitor"> ' + value. people  + '</p> <p id="time">' + value.time + '</p>' );

$.each(data, function( index, value ) {
  $("#details").append('<p id="visitor">' + value. people + '</p> <p id="time">' + value.time + '</p>' );
});

最终代码将是:

<script>
     function fetchdata() {
     $.get("http://10.10.35.138:5000/data", function (data) { //The link of this line is my api link
               $.each(data, function( index, value ) {
                     $("#details").append('<p id="visitor">' + value. people + '</p> <p id="time">' + value.time + '</p>' );
               });
           });
     }
</script>

****HTML PART****
<div class="details">
<p id="visitor">Person Count:</p>
<p id="time">Time:</p>`enter code here`
</div>

如果您的 api 数据仅包含一条价值记录,您的代码将是:

function fetchdata() {
     $.get("http://10.10.35.138:5000/data", function (data) { //The link of this line is my api link
         $("#visitor").html(data.people);
         $("#time").html(data.time);
     });
}

****HTML PART****
<div class="details">
<p id="visitor">Person Count:</p>
<p id="time">Time:</p>`enter code here`
</div>

【讨论】:

  • 先生感谢您的回复,但请建议另一种方式
  • var 间隔 = setInterval(function () { fetchdata(); }, 2000); // 先生,这段代码还包括脚本部分请帮助我
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
相关资源
最近更新 更多