Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload().
I've tried numerous approaches, but none seem to be working for me.
Below is the code I've been working with. If you can offer some guidance, I'd really appreciate it. Just show me how to do it, instead of simply providing the finished code.
HTML
<div>
<button>Get</button>
<div id="table"></div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
let myTable = document.querySelector('#table');
var distribuidores;
fetch('http://localhost:3000/distribuidores')
.then(res => res.json())
.then(data => distribuidores = data)
.then(() => console.log(distribuidores))
let headers = ['id', 'codBrid', 'descricao']
btnGet.addEventListener('click', () => {
let table = document.createElement('table');
let headerRow = document.createElement('tr');
headers.forEach(headerText => {
let header = document.createElement('th');
let textNode = document.createTextNode(headerText);
header.appendChild(textNode);
headerRow.appendChild(header);
});
table.appendChild(headerRow);
distribuidores.forEach(emp => {
let row = document.createElement('tr');
Object.values(emp).forEach(text => {
let cell = document.createElement('td');
let textNode = document.createTextNode(text);
cell.appendChild(textNode);
row.appendChild(cell);
});
table.appendChild(row);
});
myTable.appendChild(table);
});
json
{
"distribuidores": [
{
"id": "1",
"codint": "4613",
"descricao": "HTMYS"
},
{
"id": "2",
"codint": "10325",
"descricao": "MPB LTDA"
}
]
}