JSON stands for JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:
JSON.parse()
JSON file named customer.json
{ "id": 1, "name": "John Doe", "company": "123 Designs", "phone": "444-555-6666" }
Receive data from local JSON file and getting asynchronously through the XHR object and output in the browser.
document.getElementById('button1').addEventListener('click', loadCustomer); // Create a function named LoadCustomer and passing the Event Object function loadCustomer(e){ const xhr = new XMLHttpRequest(); xhr.open('GET', 'customer.json', true); xhr.onreadystatechange = function(){ if(this.readyState === 4 && this.status === 200){ const customer = JSON.parse(this.responseText); const output = ` <ul> <li>ID: ${customer.id}</li> <li>Name: ${customer.name}</li> <li>Company: ${customer.company}</li> <li>Phone: ${customer.phone}</li> </ul> `; document.getElementById('customer').innerHTML = output; } } xhr.send(); e.preventDefault(); }
Reveice an array of data from the JSON file
Create a file named customers.json
[ { "id": 1, "name": "John Doe", "company": "123 Designs", "phone": "444-555-6666" }, { "id": 2, "name": "Steve Smith", "company": "Hello Productions", "phone": "333-222-2222" }, { "id": 3, "name": "Tara Williams", "company": "Traversy Media", "phone": "111-222-3333" } ]
addEventListener
document.getElementById('button2').addEventListener('click', loadCustomers);
Load multiple customers
/ Load Customers function loadCustomers(e){ const xhr = new XMLHttpRequest(); xhr.open('GET', 'customers.json', true); xhr.onreadystatechange = function(){ if(this.readyState === 4 && this.status === 200){ const customers = JSON.parse(this.responseText); let output = ''; // We can't just output the data, we need to loop through customers.forEach(function(customer) { output += ` <ul> <li>ID: ${customer.id}</li> <li>Name: ${customer.name}</li> <li>Company: ${customer.company}</li> <li>Phone: ${customer.phone}</li> </ul> `; }); document.getElementById('customers').innerHTML = output; } } xhr.send(); e.preventDefault(); }
Leave a Reply