Last active
July 5, 2022 11:54
-
-
Save donbrae/d9ea2f9a012066931e7258e98ec85233 to your computer and use it in GitHub Desktop.
Vanilla JS Ajax/XHR request
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
function XHRRequest(url, type = 'text/plain') { | |
const request = new XMLHttpRequest(); | |
request.open('GET', `${url}?${new Date().getTime()}`, true); | |
request.setRequestHeader('Content-type', type); | |
request.onload = function () { | |
if (this.status >= 200 && this.status < 400) { // Success | |
console.log('Success', this.response); | |
} else | |
console.error('XHR error', this.response); | |
}; | |
request.onerror = function () { | |
console.error('XHR connection error'); | |
}; | |
request.send(); | |
} | |
XHRRequest('https://jsonplaceholder.typicode.com/todos', 'application/json'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment