Skip to content

Instantly share code, notes, and snippets.

@wpflames
Created November 30, 2020 17:56
Show Gist options
  • Select an option

  • Save wpflames/9add96c60bc3abf74e2d02d9961d979e to your computer and use it in GitHub Desktop.

Select an option

Save wpflames/9add96c60bc3abf74e2d02d9961d979e to your computer and use it in GitHub Desktop.
AJAX request for JSON file (local) - Single
var btn1 = document.getElementById('button1');
btn1.addEventListener('click', loadUser);
// REQUEST SINGLE USER'S DATA
function loadUser(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'assets/json/user.json', true);
xhr.onload = function(){
if(this.status = 200){
var user = JSON.parse(this.responseText);
var output = '';
output += '<ul>' +
'<li>ID: '+ user.id +'</li>' +
'<li>Name: '+ user.name +'</li>' +
'<li>Email: '+ user.email +'</li>' +
'</ul>';
document.getElementById('user').innerHTML = output;
}
}
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment