Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSilvia Ramos
Front End Web Development Techdegree Graduate 18,318 PointsAjax
OK, this may sound silly... but how does the browser know I am requesting an AJAX for the astrosUrl? or can the function below be re-used for other requests?
function getJSON(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if(xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
}
I mean, I assume, here is when we call that particular URL, isn't it? but can the above be re-used for the others URL?
btn.addEventListener('click', () => getJSON(astrosUrl));
Also, why aren't we using:
(xhr.status === 200 && xhr.readyState === 4)
?
1 Answer
Steven Parker
231,184 PointsThe "getJSON" function knows which URL to get data from because the URL is passed to it as an argument when it is called.
This function isn't re-used because it only logs the data to the console, and the other task displays it on the page.
And it's not necessary to test "readyState" since the "onload" only runs when readyState is 4.