I am trying to display some html from a json file into a div of my web site, but have only managed to get it displayed in the console. This is my code so far:
<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>
Can anyone tell me what I am missing/have done wrong? Thanks!`
Result of your function is promise, not string content. So you need to use resolved value for assignment:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With