在div中显示json html数据

时间:2018-07-11 17:16:34

标签: 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>

谁能告诉我我想念/做错了什么? 谢谢!

1 个答案:

答案 0 :(得分:1)

函数的结果是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);