Last active
November 13, 2020 09:26
-
-
Save whal-e3/97794f720a008ccdb8ae11f3802df561 to your computer and use it in GitHub Desktop.
JS Asynchronous - XHR ~ fetch API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// XHR (xmlHTTPrequest) - JSON --------------------------------------------------------------------- | |
document.getElementById('button2').addEventListener('click', loadCustomers); | |
function loadCustomers(e) { | |
const xhr = new XMLHttpRequest(); | |
xhr.open('GET', 'customers.json', true); | |
xhr.onload = function () { | |
if (this.status === 200) { | |
const customers = JSON.parse(this.responseText); | |
let output = ``; | |
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(); | |
} | |
// XHR - with external API----------------------------------------------------------------------------------- | |
document.querySelector('.get-jokes').addEventListener('click', getJokes); | |
function getJokes(e) { | |
const number = document.querySelector('input[type="number"]').value; | |
const xhr = new XMLHttpRequest(); | |
xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true); | |
xhr.onload = function () { | |
if (this.status === 200) { | |
const response = JSON.parse(this.responseText); | |
console.log(response); | |
let output = ``; | |
if (response.type === 'success') { | |
response.value.forEach(function (joke) { | |
output += `<li>${joke.joke}</li>`; | |
}); | |
} else { | |
output += `<li>Something went wrong</li>`; | |
} | |
document.querySelector('.jokes').innerHTML = output; | |
} | |
}; | |
xhr.send(); | |
e.preventDefault(); | |
} | |
// callback() ------------------------------------------------------------------------------------- | |
const posts = [ | |
{ title: 'Post One', body: 'This is post one' }, | |
{ title: 'Post Two', body: 'This is post two' } | |
]; | |
function createPost(post, callback) { | |
setTimeout(function () { | |
posts.push(post); | |
callback(); | |
}, 2000); | |
} | |
function getPosts() { | |
setTimeout(function () { | |
let output = ''; | |
posts.forEach(function (post) { | |
output += `<li>${post.title}</li>`; | |
}); | |
document.body.innerHTML = output; | |
}, 1000); | |
} | |
createPost({ title: 'Post Three', body: 'this is post three' }, getPosts); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment