繁体   English   中英

以HTML输出JSON数据

[英]Outputting JSON data in HTML

我正在尝试建立一个网站,以JSON格式显示来自URL的数据。 我试过了

<div class="jumbotron">
    <h1>
        <script>
            $(document).ready(function() {
                $.getJSON('https://some-url.com', function(data) {
                    document.write(data.attribute);
                });
            });
        </script>
    </h1>
    <p class="lead">subtitle</p>
</div>

但这会替换整个网站,而不是简单地替换h1标签中的文本。

目前,我正在尝试使用

<div class="jumbotron">
    <h1 id="replace-this"> text </h1>
        <script>
            $(document).ready(function() {
                $.getJSON('https://some-url.com', function(data) {
                    var thing = data.attribute;
                    document.getElementById("demo").innerHTML = JSON.stringify(thing);
                });
            });
        </script>
    <p class="lead">subtitle</p>
</div>

但这会保留文本,并且不会输出JSON数据。

这是一个功能齐全的示例,您的第二个示例很好,您只需要使用replace-this更改demo

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="jumbotron"> <h1 id="replace-this"> text </h1> <script> $(document).ready(function() { $.getJSON('https://jsonplaceholder.typicode.com/posts', function(data) { var thing = data; // in your case it's data.attribute document.getElementById("replace-this").innerHTML = JSON.stringify(thing, null, 4); }); }); </script> <p class="lead">subtitle</p> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM