gpt4 book ai didi

javascript - json对象的内容在javascript中转换为字符串后丢失

转载 作者:行者123 更新时间:2023-12-03 03:07:48 25 4
gpt4 key购买 nike

所以,我有一个脚本可以从服务器获取 JSON 并将其显示到页面上,JSON 中包含必须显示的 html,但由于某种原因,当我尝试将提取的 JSON(其中包含我想要的 html div)转换为字符串时,内容会丢失并且我得到一个空对象。

我想将其转换为字符串,以便innerHTML可以将其插入页面

iv'e 尝试使用 String(obj) 转换它并 obj.toString() 和 JSON.stringify 它们都返回一个空对象

仅尝试插入数据而不将其转换为字符串的事件会在页面上显示一个空对象

这是 json:

{
"content": {
"rendered": "<div id=aboutnf><p>lorem ipsum</p></div>",
"protected": false
}
}

这是 JavaScript:

function displayContents() {
//if the request succeeds display the contents
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
//parse the JSON
var JsonObj = JSON.parse(httpRequest.responseText);//parse the response
var content = JsonObj.content;
console.log(content);
var StrContent = JSON.stringify(content);
//parse the html from the json
var parser = new DOMParser();
var stuff = parser.parseFromString(StrContent, "text/html");
//get the div we want
var disp = stuff.getElementById(aboutnf);
console.log(disp);
console.log(typeof(disp));
//convert it to a string
var dispContents = String(disp);
console.log(dispContents);
//insert it to the page
document.getElementById('stuff').innerHTML = dispContents;
//if the request failed report it
} else {
alert('There was a problem with the request.');//if it fails report the fail
}
}
}

当我console.log从JSON中提取的div时,它显示的内容很好:

console.log(disp);
//returns:
<div id=aboutnf><p>lorem ipsum</p></div>

console.log(typeof(disp));
//returns:
object

但转换为字符串后:

console.log(dispContents);
//returns:
[object HTMLDivElement]

并将其插入页面会显示相同的内容:一个空的 HTMLdivElement

document.getElementById('stuff').innerHTML = dispContents;
//puts:
[object HTMLDivElement]
//on the page instead of the contents of the div

如何将 JSON 对象转换为字符串而不丢失其所有内容?

我不想为此使用 jQuery。

编辑:

我使用了 JsonObj.content.rendered,然后使用了appendchild()
从json中获取我想要的div

感谢 Nesaje、Patrick Roberts 和 nnnnnn

最佳答案

我不太明白你的问题。但我的理解是,你想要显示json数据中rendered的内容。

{
"content": {
"rendered": "<div id=aboutnf><p>lorem ipsum</p></div>",
"protected": false
}
}

我会像这样重写你的函数

function displayContents() {
//if the request succeeds display the contents
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
//parse the JSON
var JsonObj = JSON.parse(httpRequest.responseText);//parse the response
var content = JsonObj.content;
document.getElementById('stuff').innerHTML = content.rendered;
//if the request failed report it
} else {
alert('There was a problem with the request.');//if it fails report the fail
}
}
}

这会自动在 html 字段中显示 rendered 的内容。

我希望这会有所帮助。

关于javascript - json对象的内容在javascript中转换为字符串后丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com