Created
November 2, 2016 07:06
-
-
Save iansinnott/d6f913fd825f732e5908d6a1d6fa038a to your computer and use it in GitHub Desktop.
Quick XHR API intro
This file contains hidden or 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
| const ajax = (method, url, success) => { | |
| // Create the new XHR | |
| const xhr = new XMLHttpRequest(); | |
| // "Open" the request. I.e. configure its method and request URL | |
| xhr.open(method, url); | |
| // Set up a success handler. For XHR we need to respond to changes in the readyState. However, | |
| // the readyState can change for a number of reasons and we are only interested in the change | |
| // that represents completion of the request. So we check whether readyState is equal to | |
| // xhr.DONE, and if it is then we also check that the status was a success (200) | |
| xhr.onreadystatechange = () => { | |
| if (xhr.readyState === xhr.DONE && xhr.status === 200) { | |
| success(xhr.responseText); | |
| } | |
| }; | |
| // Actually send the request | |
| xhr.send(); | |
| return xhr; | |
| }; | |
| // Example: | |
| // ajax( | |
| // 'GET', | |
| // 'https://api.github.com/users/iansinnott', | |
| // (responseText) => console.log(responseText) | |
| // ); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: There is no error handling built into this function. It basically won't do anything if the server responds with a non-200 status code. This is a significant limitation, but this example is just to remind myself in a simple case how the xhr API works.