【问题标题】:Append parsed json to html将解析的 json 附加到 html
【发布时间】:2018-02-09 13:50:51
【问题描述】:

您好,我想将解析后的 json(我从 xmlhttprequest 获取)附加到 html 文件中。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>alert solr response</title>
<script src="https://code.jquery.com/jquery-3.2.1.js">
</script>
<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var json = JSON.parse(xhr.responseText);
            var data = json.facet_counts.facet_dates["dc.date.accessioned_dt"];
            delete data.gap;
            delete data.end;
            delete data.start;
            console.log(data)
            $("#test").append(data); //here is the problem, I could append xhr.Responsetext but this is not what I want
        }
    }
    xhr.open('GET', 'http://localhost:8080/solr/search/select?indent=on&rows=0&facet=true&facet.date=dc.date.accessioned_dt&facet.date.start=2016-01-01T00:00:00Z&facet.date.end=2017-12-01T00:00:00Z&facet.date.gap=%2B1MONTH&q=search.resourcetype:2&wt=json&indent=true', true);
    xhr.send(null);
</script>
</head>
<body>
<p id = "test">This is the json sample: <br></p>
</body>
</html>

我知道那里有很多类似的问题和可能的重复,很抱歉我不能将它们用于我的案例(作为一个菜鸟和所有人) 谢谢

【问题讨论】:

  • Stringify 看起来不太好并且难以阅读,我希望每个字段都在不同的行中,就像在 json 中一样
  • JSON.stringify(obj, null, 2); Go meet god
  • 如果您使用 jQuery,请给个提示,$.get()
  • $("#test").append(JSON.stringify(data, null, 2));并没有真正改变任何与 stringify(data) 相似的东西
  • 知道了,谢谢

标签: javascript jquery json xmlhttprequest


【解决方案1】:

如果您使用 jQuery,您可以稍微简化这一点,当您获取数据时,您可以使用第三个参数获得 stringify 内容以获得所需的缩进,因为它只是纯文本,您还必须附加将其设置为 &lt;pre&gt; 标签或将 p 标签处的 css 设置为:white-space: pre

$.get('https://httpbin.org/get').then(function(data) {
  delete data.gap;
  delete data.end;
  delete data.start;

  $("#test").text(JSON.stringify(data, null, 2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="test"></pre>

【讨论】:

  • OP 想要解析然后删除一些 json 元素,你的 jquery 代码中没有解析部分。
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 2021-12-26
  • 2010-12-31
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多