Skip to content

Instantly share code, notes, and snippets.

@tamalchowdhury
Last active August 30, 2020 08:03
Show Gist options
  • Save tamalchowdhury/badd8442661cbb4985ddb5a2a3d224c7 to your computer and use it in GitHub Desktop.
Save tamalchowdhury/badd8442661cbb4985ddb5a2a3d224c7 to your computer and use it in GitHub Desktop.
Update page content with data from JSON API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Example testing api</h1>
<button id="button">Do something</button>
<table style="width: 100%;">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tbody id="tcontent"></tbody>
</table>
<script src="./script.js"></script>
</body>
</html>
document.getElementById('button').addEventListener('click', doSomething);
function doSomething() {
console.log('I am doing something');
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => {
let content = ``;
json.forEach((element) => {
console.log(element.id, element.title, element.body);
content += `<tr>
<td>${element.id}</td>
<td>${element.title}</td>
<td>${element.body}</td>
</tr>`;
});
document.getElementById('tcontent').innerHTML = content;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment