4 ms·
if (xhr.readyState !== 4) return; is gross and stateful. Certainly you can learn it and use it but .then((res) => res.json()) is much more declarative.
by ARandomerDude 5y ago
if (xhr.readyState !== 4) return;
is gross and stateful. Certainly you can learn it and use it but
.then((res) => res.json())
is much more declarative.
- mmis1000 5y agoAnd if you forgot to call xhr.send() at the end. You screw up and your callback is never called. fetch doesn't even allow you to make this kind of mistakes.
- Beltalowda 5y agoIt allows you take make other mistakes, such as using the wrong type for POST data resulting in "[object Object]" and similar gibberish being sent to the server. Not saying XMLHttpRequest API's is brilliant, but fetch's API also doesn't exactly fill me with joy.
- ARandomerDude 5y agoI think the key is the comparative "-er" in "cleaner" and "simpler." Fetch may not be the cleanest or simplest possible solution, but in my opinion it is cleaner and simpler. XMLHttpRequest is good. Fetch is better.
- iostream24 5y agoAnd I have the entirety of an XMLHttpRequest in my head anyway, that xhr.send(fd); is where you included your form data… These strange notions of burden and beauty…
- Jasper_ 5y agoYou don't need to check readyState; onload is only called when the readyState switches to 4.
- petre 5y agoAt least fetch is a viable replacement for jQuery.ajax and the syntax is quite similar.