[英]JSON in HTML with line breaks
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
中的结果也在多行并缩进?
.box is just an empty div.
.box只是一个空div。
Make it an empty <pre>
instead: 改为空
<pre>
:
<pre class="box"></pre>
I agree with using <pre>
, but another option is to replace all \\n
with <br>
elements, and spaces with
我同意使用
<pre>
,但另一种选择是将所有\\n
替换为<br>
元素,将空格替换为
. 。 It's probably really unnecessary (since
<pre>
preserves the whitespace). 它可能真的没必要(因为
<pre>
保留了空白)。 You can try: 你可以试试:
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);
DEMO: http://jsfiddle.net/Yk5Pb/3/ 演示: http : //jsfiddle.net/Yk5Pb/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.