karlakmkj

Reconstruct XHR GET request

Dec 30th, 2020 (edited)
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //boilerplate code for an AJAX GET request using an XMLHttpRequest object.
  2. const xhr = new XMLHttpRequest();    //common practice to name this object xhr
  3.  
  4. const url = 'https://api-to-call.com/endpoint';
  5.  
  6. xhr.responseType = 'json';    //the response is going to be formatted into JSON type
  7. xhr.onreadystatechange = () => {    //make the event handler equal to an anonymous arrow function
  8.   if (xhr.readyState === XMLHttpRequest.DONE) {     //Purpose of this conditional statement checks to see if the request has finished
  9.     return xhr.response;
  10. }
  11. }
  12.  
  13. xhr.open('GET', url);    //.open() creates a new request and the arguments passed in determine the type and URL of the request.
  14. xhr.send();    //send the request to the server.
Add Comment
Please, Sign In to add comment