Last active
October 9, 2024 15:29
-
-
Save garsaud/1526379593ac5b0947f49b40ca3f87d7 to your computer and use it in GitHub Desktop.
Vanilla JS ajax
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
// Using with(){} — Deprecated but practical | |
with (new XMLHttpRequest()) { | |
open('get', 'search?q='+encodeURIComponent('chaises'), true); | |
onreadystatechange = function () { | |
if (readyState !== 4 || status !== 200) return; | |
console.log(JSON.parse(responseText)); | |
}; | |
send(); | |
} | |
// The classic way | |
var xhr = new XMLHttpRequest(); | |
xhr.open('get', 'search?q='+encodeURIComponent('chaises'), true); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState !== 4 || xhr.status !== 200) return; | |
console.log(JSON.parse(xhr.responseText)); | |
}; | |
xhr.send(); | |
// Post request + es6 + synchronous | |
const xhr = new XMLHttpRequest(); | |
xhr.open('post', url, false); | |
xhr.onreadystatechange = () => xhr.status === 200 && document.location.reload(); | |
xhr.send(formData); | |
// Proxying XHR | |
var originalXhrOpen = window.XMLHttpRequest.prototype.open; | |
window.XMLHttpRequest.prototype.open = function() { | |
console.log(arguments); | |
this.addEventListener("readystatechange", function () { | |
console.log(this); | |
}, false); | |
return originalXhrOpen.apply(this, [].slice.call(arguments)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment