In the example below we set up a fetch function to get data from a set API.
Create a new folder
Create a index.html and script.js file
Create a basic html template. The one below includes a lot of extras like Bulma and Jquery which is required.
Below is the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bulma/1.0.0/css/bulma.min.css">
<title>Fetch Data template</title>
</head>
<body>
<div class="container">
<h1 class="title">Fetch Data Example</h1>
<div id="output">
</div>
</div>
<!-- link to your script -->
<script src="script.js"></script>
</body>
</html>
Below is the JavaScript file which fetches data from a shark attack database and print the names of the victims onto your page.
var data;
var output = document.getElementById("output");
fetchAllData(); //start fetching data on load
//get the data from the api and parse to data as JSON.
async function fetchAllData() {
try {
const response = await fetch('https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/global-shark-attack/records?where=country%3D%22Australia%22%20OR%20country%20%3D%20%22AUSTRALIA%22&limit=100');
data = await response.json();
printData();
} catch (error) {
console.error(error);
}
}
//loop over the data and print to the output div
function printData() {
var text = "";
data.results.forEach(element => {
console.log(`Name: ${element.name} - ${element.country} - ${element.area}`);
text += `Name: ${element.name} - ${element.country} - ${element.area}<br>`;
});
output.innerHTML = text;
}