Get Local Text File Data
function getText() { fetch('test.txt') .then(res => res.text()) .then(data => { console.log(data); document.getElementById('output').innerHTML = data; }) .catch(err => console.log(err)); }
Get Local JSON Data
function getJson() { fetch('posts.json') .then(res => res.json()) .then(data => { console.log(data); // This is an array so we have to loop through it let output = ''; data.forEach(function(post){ output += `<li>${post.title}</li>`; }); document.getElementById('output').innerHTML = output; }) .catch(err => console.log(err)); }
Get External API Data
function getExternal() { fetch('https://api.github.com/users') .then(res => res.json()) .then(data => { console.log(data); let output = ''; data.forEach(function(user){ output += `<li>${user.login}</li>`; }); document.getElementById('output').innerHTML = output; }) .catch(err => console.log(err)); }
Leave a Reply