我正在尝试在新窗口中以可读格式显示 json。我有一个按钮,当您单击时,会出现一个新选项卡,其中包含 json。但是,在新窗口中,json 仍然没有格式化,它显示为纯文本。然而,在 console.log
中,它的格式正确。我不明白为什么会不一样。
$('.showRawJson').click(function () {
$.getJSON('somelink', function (json) {
var myjson = JSON.stringify(json, null, 2);
// In the console the json is well formatted
console.log(myjson);
var x = window.open();
x.document.open();
// Here in the new tab the json is NOT formatted
x.document.write(myjson);
x.document.close();
});
});
最佳答案
将其放入pre
标签中,显示时会保留空白。您的代码发生了一些变化:
var myjson = JSON.stringify(json, null, 2);
console.log(myjson);
var x = window.open();
x.document.open();
x.document.write('<html><body><pre>' + myjson + '</pre></body></html>');
x.document.close();
关于javascript - 在新选项卡中以可读格式显示 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705640/