![]() ![]() XHR is cross platform, and if you want to support IE < 9 you need only 2 extra checks. Same you don’t have different checks to grab fetch, because it’s not cross platform. You don’t have 3 different checks … nobody does. And if you're looking for a polyfill, check out GitHub's implementation. For a more in depth look, please visit Introduction to Fetch. This is meant to be an introduction to fetch. I can't wait until fetch is more broadly supported! ![]() After all, it was created so that we could do AJAX the right way fetch has the advantage of hindsight. The new fetch API seems much saner and simpler to use than XHR. While fetch is a nicer API to use, the API current doesn't allow for canceling a request, which makes it a non-starter for many developers. Very easy, very eye-pleasing as well! Unwritten Story Posting Form DataĪnother common use case for AJAX is sending form data - here's how you would use fetch to post form data:īody: new FormData(document.getElementById('comment-form'))Īnd if you want to POST JSON to the server:Įmail: document.getElementById('email').value,Īnswer: document.getElementById('answer').value The blob() method of the Body mixin takes a Response stream and reads it to completion. If you want to load an image via fetch, for example, that will be a bit different:ĭocument.querySelector('img').src = URL.createObjectURL(imageBlob) You can get the response text via chaining the Promise's then method along with the text() method. JSON isn't always the desired request response format so here's how you can work with an HTML or text response: Of course that's a simple JSON.parse(jsonString), but the json method is a handy shortcut. Let's say you make a request for JSON - the resulting callback data has a json method for converting the raw data to a JavaScript object:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |