JAVASCRIPT FETCHING JSON USING XMLHttpRequest()
Index.html I have this basic HTML that will use to display data from JSON file, here is the code below.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Javascript Fetch JSON FILE</title> <link rel="shortcut icon" href="data:" type="image/x-icon"> </head> <body> <div class="output"></div> <script src="./app.js"></script> </body> </html>App.js is where the JavaScript magic happens to fetch the JSON file.
const url = './data.json';Below is the JSON file that I use, you can create your own and explore, this is just for testing that will let us display data using XML http request.const output = document.querySelector('.output');let xHR = new XMLHttpRequest();console.log(xHR)xHR.open('GET', url);xHR.responseType = 'json';xHR.onload = function() {console.log(xHR.response);let data = xHR.response;data.books.forEach(result => {output.innerHTML += `§{result.title}<br />`;}) }xHR.send(); console.log(xHR);
{
"books": [
{
"title": "Learn to Code",
"author": "Bryan Devs",
"isbn": "324-23243"
},
{
"title": "The Adventure JSON",
"author": "Jason Jones",
"isbn": "3324-2-444"
},
{
"title": "New Objects",
"author": "Jane Doe",
"isbn": "2343-234-2433"
}
]
}
0 comments:
Post a Comment