Skip to content

Instantly share code, notes, and snippets.

@gregoryhammond
Last active Jun 15, 2021
Embed
What would you like to do?
JavaScript Fetch api results on page
/* This is under Unlicense(https://unlicense.org/) and/or CC0(https://www.tldrlegal.com/l/cc0-1.0). */
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title>Fetch API Local</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="nameHere"></div>
<script>
fetch('https://fakerapi.it/api/v1/persons?_quantity=4')
// Thanks to https://www.educba.com/javascript-fetch-api/ for the guidance
// thanks https://stackoverflow.com/a/51417451 for explaining why it should be response here
.then(response => response.json())
.then(function (dataIn)
{
// to run the appendData function (bring in dataIn which has the object with all the data as an object)
appendData(dataIn);
})
.catch (function (err)
{
console.log('Error: ' + err);
});
function appendData(dataIn)
{
/* For loop, which loops through each item and gets the firstname and last name and puts in on a new line.
Guidance from: https://stackoverflow.com/a/12996885, https://stackoverflow.com/a/19529473
*/
for (var i = 0; i != dataIn.total; i++)
{
document.getElementById("nameHere").innerHTML += 'Name is: ' + dataIn.data[i].firstname + ' ' + dataIn.data[i].lastname + '<br>';
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment