Fetch API is a new standard for dealing with http requests.
Get Local Text File Data
document.getElementById('button1').addEventListener('click', getText); function getText() { fetch('test.txt') .then(function(res){ return res.text(); }) .then(function(data) { console.log(data); document.getElementById('output').innerHTML = data; }) .catch(function(err){ console.log(err); }); }
Get Local JSON Data
document.getElementById('button2').addEventListener('click', getJson); // Get local json data function getJson() { fetch('posts.json') .then(function(res){ return res.json(); }) .then(function(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(function(err){ console.log(err); }); }
Get external API data
document.getElementById('button3').addEventListener('click', getExternal); function getExternal() { fetch('https://api.github.com/users') .then(function(res){ return res.json(); }) .then(function(data) { console.log(data); // This is an array so we have to loop through it let output = ''; data.forEach(function(user){ output += `<li>${user.login}</li>`; }); document.getElementById('output').innerHTML = output; }) .catch(function(err){ console.log(err); }); }
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" /> <link rel="icon" href="#"> <title>Ajax Sandbox</title> </head> <body> <div class="container"> <h1>Fetch API Sandbox</h1> <button id="button1">Get Text</button> <button id="button2">Get JSON</button> <button id="button3">Get API Data</button> <br><br> <div id="output"></div> </div> <script src="app.js"></script> </body> </html>
Leave a Reply