javascript - 如何将 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>
但这也行不通。
解决方案
您可以考虑使用 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);
});
推荐阅读
- javascript - $ 不带选择器的符号 JQuery
- git - git rebase -i HEAD~N 返回超过 N 次提交
- javascript - 使用 Javascript 和 PHP 使用 datalist 选择多个选项
- python-3.x - 如何从输入中过滤字母和符号?
- java - 我通过settext将数据放入textview,但它不起作用
- r - 使用 XPath 通过 XML 包获取元素值 (R)
- java - Spring中的@DateTimeFormat给出了错误的日期
- excel - 查找今天日期的第一次出现并在上方插入行
- r - 编写回归函数时出现错误 0(非 NA)案例
- c++ - 在c ++中对对象数组进行排序,重复值