Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Async Programming and Callback Functions

Ajax

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
Steven Parker
210,423 Points

The "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.