Converting jQuery to Vanilla Javascript: Ajax via Fetch
Posted: 12/1/2021 12:36:17 PM
By: PrintableKanjiEmblem
Times Read: 1,258
0 Dislikes: 0
Topic: Programming: jQuery/Javascript

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.

The fetch specification differs from jQuery.ajax() in the following significant ways:

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn’t in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.
  • fetch() won’t send cross-origin cookies unless you set the credentials init option. (Since April 2018. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)

A basic fetch request is really simple to set up.

Read More at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Rating: (You must be logged in to vote)