首页 > 解决方案 > 如何将 Internet 上的 JSON 文件中的数据显示为我网站上的 HTML?

问题描述

在https://ipapi.co/json/有一个方便的 IP 跟踪器。我希望我网站的查看者在网页底部看到他们的 IP 地址。我现在拥有的是:

<div class="container">
  <div id="IP">IP Address should show here.</div>
  <script>
    document.getElementById('IP').innerHTML = (https://ipapi.co/json/).ip;
  </script>
</div>

但是,这不会显示 IP 地址。我可能使用了错误的方法。如何让它正确显示?

编辑:我试着做:

<div class="container">
  <div id="IP">IP Address should show here.</div>
  <script>
    fetch('https://ipapi.co/json/')
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        document.getElementById('IP').innerHTML = JSON.stringify(myJson.ip);
      });
  </script>
</div>

但这也行不通。

标签: javascripthtmljson

解决方案


您可以考虑使用 javascript Fetch API

在你的情况下,它可能是这样的:

fetch('https://ipapi.co/json/')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    document.getElementById('IP').innerHTML = JSON.stringify(myJson.ip);
  });

推荐阅读