javascript - 在 div 中显示 json html 数据

标签 javascript html json fetch

我正在尝试将 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/

相关文章:

javascript - jquery函数重载

javascript - 每天运行一次代码

html - 模糊 Bootstrap 导航栏,而不模糊其中的内容

javascript - Chrome 中的 CSS 延迟加载

javascript - 在 jquery 中创建新的垂直 json 到水平

javascript - 有没有一种安全的方法来防止 exec 剥离引号?

javascript - 确定用户在应用程序中的位置并加载不同的 Angular 脚本

javascript - jQuery向上遍历并找到

css - 如何应用作用域样式表?

c# - 如何解析会导致非法 C# 标识符的 JSON 字符串?