You don't need jQuery (3) New AJAX method fetch (), jqueryfetch

Source: Internet
Author: User

You don't need jQuery (3) New AJAX method fetch (), jqueryfetch

XMLHttpRequest to complete ajax is outdated.

Fetch () allows us to complete ajax functions like XMLHttpRequest (XHR. The main difference between them is that the Fetch API uses Promises, which makes the interface simpler and simpler, avoids the complexity of callback, and eliminates the need to use the complex XMLHttpRequest API.

If you have never used Promises before, you should first read the article JavaScript Promises usage.

I. Basic Fetch usage

Let's use an example to compare the differences between XMLHttpRequest and fetch. We need to request a URL to obtain the returned results in JSON format.

XMLHttpRequest
An XMLHttpRequest request requires two listeners to capture success and error, and calls the open () and send () methods.

function reqListener() {  var data = JSON.parse(this.responseText);  console.log(data); }function reqError(err) {  console.log('Fetch Error :-S', err); }var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.onerror = reqError; oReq.open('get', './api/some.json', true); oReq.send();

Fetch
The code of our fetch request is basically like this:

fetch('./api/some.json')  .then(  function(response) {   if (response.status !== 200) {   console.log('Looks like there was a problem. Status Code: ' +    response.status);   return;   }  // Examine the text in the response   response.json().then(function(data) {   console.log(data);   });  }  )  .catch(function(err) {  console.log('Fetch Error :-S', err);  });

We first check whether the request response status is 200, and then analyze the response data according to the JSON object.

The content obtained by the fetch () request is a Stream object. That is to say, when we call the json () method, the returned result is still a Promise object, because stream reading is asynchronous.

Returns Metadata of a Data Object (Metadata)

In the above example, I saw the basic status of the server Response object Response and how to convert it to JSON. There is a lot of metadata information in the Response object returned, which is as follows:

fetch('users.json').then(function(response) {  console.log(response.headers.get('Content-Type'));  console.log(response.headers.get('Date')); console.log(response.status);  console.log(response.statusText);  console.log(response.type);  console.log(response.url); });

Response object Response type

When we execute a fetch request, the response data type response. type can be "basic", "cors", or "opaque ". These types are used to explain how to treat the data and data sources.

When a request is initiated from the same domain, the response type will be "basic". At this time, there will be no restrictions on the use of the response content.

If the request comes from another domain and the response has CORs header information, the response type will be "cors ". The responses of the "cors" and "basic" types are basically the same. The difference is that the response of the "cors" type limits that you can only see header information including 'cache-control ', 'content-Language', 'content-type', 'expires', 'last-modified', and 'pragm '.

The response of the "opaque" type indicates that the request comes from another domain and does not have CORS header information. An opaque-type response cannot be read, and cannot be read to the Request status. You cannot see whether the request is successful or not. The current fetch () implementation cannot execute such a request.

You can specify a mode for a fetch request to only execute requests in the specified mode. This mode can be divided:

"Same-origin"Only requests from the same domain can be successful, and other requests will be rejected.
"Cors"Requests from different domains are allowed, but correct CORs header information is required.
"Cors-with-forced-preflight"Run preflight check before executing a real call.
"No-cors"Currently, this mode cannot be executed.
The method for defining the mode is to use a parameter object as the second parameter of the fetch method:

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})  .then(function(response) {  return response.text();  })  .then(function(text) {  console.log('Request successful', text);  })  .catch(function(error) {  log('Request failed', error)  });

Concatenate Promises

One of the biggest features of Promises is that you can concatenate various operations. For fetch, we can share some logical operations in each fetch operation.

When using the json api, we need to check the status of each request response and parse it into a JSON object. With promise, we can simply put the analysis status and JSON parsing code into a separate function, and then return the code as a promise. This makes the code more organized.

function status(response) {  if (response.status >= 200 && response.status < 300) {  return Promise.resolve(response)  } else {  return Promise.reject(new Error(response.statusText))  } }function json(response) {  return response.json() }fetch('users.json')  .then(status)  .then(json)  .then(function(data) {  console.log('Request succeeded with JSON response', data);  }).catch(function(error) {  console.log('Request failed', error);  });

We use the status function to check response. status and return the results of Promise. resolve () or Promise. reject (). This result is also a Promise. In our fetch () call chain, if the execution result of fetch () is resolve, then the json () method is called. This method returns a Promise, in this way, a JSON object after analysis is obtained. If the analysis fails, the reject function and the catch statement are executed.

You will find that in fetch requests, we can share some business logic to make the code easier to maintain and more readable and testable.

Execute form data submission with fetch

In WEB applications, submitting forms is very common, and using fetch to submit form data is also very simple.

The method and body parameters are provided in fetch.

fetch(url, {  method: 'post',  headers: {   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"  },  body: 'foo=bar&lorem=ipsum'  }) .then(json)  .then(function (data) {  console.log('Request succeeded with JSON response', data);  })  .catch(function (error) {  console.log('Request failed', error);  });

Send user identity creden in the Fetch request

If you want to attach credentials such as cookies to a fetch request, you can set the credentials parameter to "include.

fetch(url, {  credentials: 'include' })

Obviously, the fetch API is much simpler than the traditional XMLHttpRequest (XHR) API, and is no inferior to the ajax API provided in jQuery.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.