Asynchronous request xhr, ajax, axios compared with the difference between the fetch

why: Why is there a different way to do that?
what: These are methods of asynchronous data request. In the case of not reload the page to communicate with the server, exchange data, or update the page.
how: They have their own characteristics.

1. XMLHttpRequest Object

Modern browser, most start to exchange data with the server, all through the XMLHttpRequest object. It can send and receive data using the format JSON, XML, HTML text and text and so on.
It has brought us many benefits .

  1. Update page without reloading the page
  2. Request / receive data from the server after the page has loaded
  3. Send data to the server in the background.

However, it also has some disadvantages :

  1. Is also more complicated, you need to set a lot of value.
  2. Early IE browser has its own implementation, so you need to write compatible code.
if (window.XMLHttpRequest) { // model browser
  xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // IE 6 and older
  xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.open('POST', url, true)
xhr.send(data)
xhr.onreadystatechange = function () {
  try {
    // TODO 处理响应
    if (xhr.readyState === XMLHttpRequest.DONE) {
      // XMLHttpRequest.DONE 对应值是 4
      // Everything is good, the response was received.
      if (xhr.status === 200) {
        // Perfect!
      } else {
        // There was a problem with the request.
        // For example, the response may hava a 404 (Not Found)
        // or 500 (Internal Server Error) response code.
      }
    } else {
      // Not ready yet
    }
  } catch (e) {
    // 通信错误的事件中(例如服务器宕机)
    alert('Caught Exception: ' + e.description)
  }
}

2. jQuery ajax

In order to more efficient operation DOM, and avoid some of the browser compatibility problems, created jQuery. It is inside the AJAXrequest is also compatible with various browsers, you can have a simple and easy way $.get, $.post. Simply put, it is to XMLHttpRequestpackage objects.

$.ajax({
  type: 'POST',
  url: url, 
  data: data,
  dataType: dataType,
  success: function () {},
  error: function () {}
})

Advantages :

  1. Of primary XHRpackaging, made compatible with the process, it simplifies the use.
  2. Added JSONPsupport can be simply cross-domain processing section.

Disadvantages :

  1. If there are multiple requests, and there is a dependency, then the callback hell easily formed.
  2. Itself is programmed for the MVC, MVVM does not meet the front end of the wave of now.
  3. ajax is a jQuery method. If you just want to use jQuery ajax it has to introducing a whole is very unreasonable.

3. axios

AxiosIt is based on promisea HTTPlibrary that can be used in the browser and node.jsin. It is also the essence of the original XMLHttpRequestpackage, but it is implemented version of Promise, in line with the latest ES specification.

axios({
    method: 'post',
    url: '/user/12345',
    data: {
      firstName: 'liu',
      lastName: 'weiqin'
    }
  })
  .then(res => console.log(res))
  .catch(err => console.log(err))

After Vue2.0, especially the rain the river greatly recommend that you use axiosto request data.
Advantages :

  1. Created from the browserXMLHttpRequests
  2. From node.jscreation httprequest
  3. Support PromiseAPI
  4. Intercept request and response
  5. Conversion request data and response data
  6. Cancellation request
  7. Automatic conversion JSONdata
  8. Client support defense XSRF

Disadvantages :

  1. Only holders modern generation of browsers.

4. fetch

Fetch APIProvides an JavaScriptinterface for accessing and manipulating HTTPportion of the duct, for example, requests and responses. It also provides a global fetch()method which provides a simple and reasonable way to access resources across the network asynchronously.
fetchLow-level API, instead of XHR, you can easily handle a variety of formats, non-text format. It can easily be used by other technologies, such as Service Workers. But want to use a good fetch, you need to do some package deal.

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Advantages: cross-domain process
in the configuration, add a mode: 'no-cors'can of cross-domain

fetch('/users.json', {
    method: 'post', 
    mode: 'no-cors',
    data: {}
}).then(function() { /* handle response */ });

fetchThe current problems encountered :

  1. fetchOnly given to the network a request for 400, 500both as a successful request, to processing needs to be encapsulated
  2. fetchDefault will not take cookie, you need to add configuration items.
  3. fetchIt does not support abort, does not support timeout control, use setTimeoutand Promise.rejectimplementation of control does not prevent timeout request process continues to run in the background, resulting in a waste flow.
  4. fetchThere is no way to monitor the progress of native request, and XHRcan be.

Please note that fetchspecification and jQuery.ajax()there are two different ways, to keep in mind:

- When receiving the error representative of a HTTP 状态码time from fetch()the return Promise it will not be marked as Reject , even if the state of the HTTP response codes are 404or 500. Instead, it Promise 状态is marked as resolve(but will resolvereturn the value of okthe attribute set false) only when a network failure or the request is blocked, will be labeled reject.

- By default, fetch does not send or receive any cookies from the server , if the site is dependent on the user session, unauthenticated request will result in (to be sent cookies, you must set credentialsthe option).

reference

  1. MDN- use Fetch
  2. Watching clouds -axios Instructions
  3. jQuery ajax()
  4. XMLHttpRequest

Guess you like

Origin www.cnblogs.com/weiqinl/p/11279950.html