Better AJAX API

von Merle Ehm (Kommentare: 0)

Do you still make AJAX request this way (jQuery style)?

$.ajax({ 
   type: "GET", 
   url: "/some/url", 
   success: function(response) { 
     console.log(response);
   } 
});

Or do you even use the odd XMLHttpRequest object like this?

const request = new XMLHttpRequest();
request.addEventListener("load", function() { 
   console.log(this.responseText); 
}); 
request.open("GET", "/some/url"); 
request.send();

At long last there is a better way now. Isn't this API very neat?

fetch('/some/url').then(function(response) { 
   return response.text(); 
}).then(function(text) { 
   console.log(text);
});

The Fetch API uses Promises (see ".then(...)" in code snippet above) instead of callback functions. These Promises make it easier to control the flow of multiple asynchronous actions. You can read more about Promises here.

The best about the Fetch API, you can already use it in the following browser versions upwards:

Chrome Edge Firefox Opera Safari
42 14 39 29 10.1
Android Web View Chrome for Android Safari Mobile
42 14 39

(also see support table on Can I Use...)

Oh, I love this API! For more information read the docs from Mozilla Developer Network.

Zurück