Native XHR objects

Modern browsers, they start by exchanging data with the server, using XMLHttpRequest objects. It can send and receive data using JSON, XML, HTML, and text text formats.

Benefits: Update the page without reloading the page request/receive data from the server after the page is loaded and send data to the server in the background.

Disadvantages: Tedious to use and requires many values to be set. Early Internet Explorer browsers had their own built-in objects, which required writing compatible code to determine whether they were XMLHttpRequest objects.

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 processes the responseif(xhr.readyState === xmlHttprequest. DONE) {// xmlhttprequest. DONE is 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) {// Communication error events (such as server downtime) alert('Caught Exception: ' + e.description)
  }
}
Copy the code

The $. In the jQuery ajax

To facilitate dom manipulation and avoid browser compatibility issues, jquery was created with AJAX requests that are compatible with different browsers and can be used directly with.get,.pist. It is a layer of encapsulation of the XMLHttpRequest object

Advantages: native XHR packaging, compatible processing, simplified use. Added support for JSONP to make it easy to handle partial cross-domains.

Cons: Easy callback hell if you have multiple requests and dependencies. Itself is for MVC programming, not in line with the current wave of front-end MVVM. Ajax is a method in jQuery. It doesn’t make sense to introduce the entire jQuery if you’re just going to use Ajax.

axios

Axios is a Promise-based HTTP library that can be used in browsers and Node.js. It’s essentially a wrapper around native XMLHttpRequest, but it’s an implementation version of Promise that meets the latest ES specification.

Advantages:

  1. Create XMLHttpRequests from the browser
  2. Create HTTP requests from Node.js
  3. Supporting Promise API
  4. Intercept requests and responses
  5. Transform request data and response data
  6. Cancel the request
  7. Automatically convert JSON data
  8. Client support prevents CSPRF
  9. Provides some interfaces for concurrent requests

Cons: Only supports modern generation browsers.

axios({
    method: 'post',
    url: '/userlist/all',
    data: {
      id: '1',
      page:1,
      limit: 20
    }
  })
  .then(res => console.log(res))
  .catch(err => console.log(err))
Copy the code

fetch

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, which provides a simple, reasonable way to fetch resources asynchronously across a network.

Fetch is a low-level API that replaces XHR and can easily handle a variety of formats, non-textual formats. It can be easily used by other technologies, such as Service Workers. But to use FETCH well, you need to do some wrapping.

fetch('http://acccess/.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) { console.log(myJson); }); // Add mode to the configuration:'no-cors'Fetch ()'/users.json', {
    method: 'post', 
    mode: 'no-cors',
    data: {}
}).then(function() { /* handle response */ });
Copy the code

Advantages:

2. Based on standard promise implementation, support async/await 3. More low-level, the API is rich (Request,response) 4. Out of XHR, is a new implementation in the Es specification

Disadvantages:

1. Support network error, which means it calls reject only when a network error causes the request to fail. It does not reject 400,500 errors. The cookies are not configured by default. Fetch (URL,{credentials: ‘include’}) 3. Abort is not supported and timeout control is not supported. SetTimeout and Promise. reject do not prevent the request process from running in the background, resulting in a waste of traffic

1 When an HTTP status code representing an error is received, the Promise returned from fetch() is not marked as reject, even if the HTTP response has a 404 or 500 status code. Instead, it marks the Promise state as resolve (but sets the OK attribute of the return value of resolve tofalse), marked reject only when the network fails or the request is blocked. In this case, fetch does not send or receive any cookies from the server, which results in unauthenticated requests if the site relies on the user session (to send cookies, the Credentials option must be set).Copy the code