javascript 带换行符的 HTML 中的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16499804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON in HTML with line breaks
提问by Oskar Persson
I have some Javascript on my page that makes an ajax call which returns some JSON data.
我的页面上有一些 Javascript 可以进行 ajax 调用,返回一些 JSON 数据。
With the result I do this:
结果我这样做:
results = JSON.stringify(data, undefined, 2);
console.log(results);
$('.box').append(results);
.box
is just an empty div.
.box
只是一个空的div。
console.log(results)
gives me an indented result with linebreaks but the data in .box
is just all in one line.
console.log(results)
给我一个带有换行符的缩进结果,但数据.box
只是在一行中。
How can I make sure that the result in .box
is also on multiple lines and indented?
我怎样才能确保结果.box
也在多行上并缩进?
回答by Darin Dimitrov
.box is just an empty div.
.box 只是一个空的 div。
Make it an empty <pre>
instead:
<pre>
改为空:
<pre class="box"></pre>
回答by Ian
I agree with using <pre>
, but another optionis to replace all \n
with <br>
elements, and spaces with
. It's probably really unnecessary (since <pre>
preserves the whitespace). You can try:
我同意使用<pre>
,但另一种选择是\n
用<br>
元素替换 all ,用
. 这可能真的没有必要(因为<pre>
保留了空格)。你可以试试:
var data = {key1: "value1", key2: "value2", key3: {key4: "value4"}},
results = JSON.stringify(data, undefined, 2),
results2 = results.replace(/\n/g, "<br>").replace(/[ ]/g, " ");
console.log(results);
$(".box").append(results2);