我正在尝试将 json 文件中的一些 html 显示到我网站的 div 中,但只设法让它显示在控制台中。 到目前为止,这是我的代码:
<div id="customSidebar" onload="sidebarContent()">
</div>
<style>
#customSidebar {
background-color: green;
position: fixed;
top: 120px;
left: 100px;
z-index: 100000;
width: 300px;
min-height: 300px;
height: auto;
}
</style>
<script>
function sidebarContent(){
fetch('*url*', {
headers: {
'Accept': 'application/json, text/plain, */*'
}
})
.then(response => {
return response.json().then(data => {
if (response.ok) {
return data.mainContent;
} else {
return Promise.reject({status: response.status, data});
}
});
})
.then(result => console.log('success:', result))
.catch(error => console.log('error:', error));
}
document.getElementById('customSidebar').innerHTML = sidebarContent();
</script>
谁能告诉我我错过了什么/做错了什么? 谢谢!`
最佳答案
您的函数的结果是 promise ,而不是字符串内容。所以你需要使用解析值进行赋值:
function sidebarContent() {
return fetch('*url*', {
headers: {
'Accept': 'application/json, text/plain, */*'
}
})
.then(response => {
return response.json().then(data => {
if (response.ok) {
return data.mainContent;
} else {
return Promise.reject({ status: response.status, data });
}
});
});
}
sidebarContent().then(content => document.getElementById('customSidebar').innerHTML = content);
关于javascript - 在 div 中显示 json html 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51291051/