The introduction

Front end can be a rapid rise of the beginning of the development of the unceasing evolution, the emergence of a new Api, new features, front end this areas is really a very fast development, the use of just the day before you learn to XXX, XXX is a day after the innovation, a new technology, you learn at lamenting the motionless at the same time, have to continue to learn. Anyway, back to today’s topic…

3 years ago when I joined the company, I was a rookie who only knew how to use Ajax and Jquery Ajax. Since Jquery did not support large file requests in the early days, I could solve the problem with native XHR.

The following space is longer, it is suggested to collect slowly watch. What you learn here will definitely help you

Difference is introduced

“Ajax” :

Asynchronous JavaScript and XML (Asynchronous JavaScript and XML) Asynchronous JavaScript and XML (Asynchronous JavaScript and XML) Asynchronous JavaScript and XML (Asynchronous JavaScript and XML) There will be callback hell.

“Jquery Ajax” :

Is the underlying AJAX implementation of jQuery. Easy to use high-level implementations see $. Get, $. Post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you don’t need to manipulate this function directly, unless you need to manipulate unusual options for more flexibility. JQuery Ajax-Ajax () method

“Axios” :

Axios is not native JS and needs to be installed. It can be used not only on the client side, but also on the NodeJS side. Axios can also intercept in the request and response phases. It’s also based on the Promise object. Features: Create XMLHttpRequests from the browser, create HTTP requests from Node.js, support the Promise API, intercept requests and responses, and more. Axios Chinese document portal

“Fetch” :

Fetch provides a generic definition of Request and Response (and other objects related to network requests). It can be used in more applications in the future, whether it is service workers, Cache APIS, or other ways of handling requests and responses, or even any way that requires you to generate your own responses in your application. Fetch, billed as an alternative to AJAX, was introduced in ES6, using Promise objects in ES6. Fetch is designed based on Promise. Fetch’s code structure is much simpler than Ajax, and the parameters are a bit like jQuery Ajax. However, keep in mind that FETCH is not a further encapsulation of Ajax, but rather native JS. The Fetch function is native JS and does not use an XMLHttpRequest object.

Detailed talk

Describe the differences between Ajax,jQuery, Ajax, Axios and FETCH in detail. Let’s continue our research.

AJAX = asynchronous JavaScript and XML.

AJAX is a technique for creating fast, dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that part of a web page can be updated without reloading the entire page.

How AJAX works

A, Ajax

XMLHttpRequest makes it easy to send an HTTP request. You simply create a request object instance, open a URL, and send the request. When the transfer is complete, the HTTP status of the result and the content of the returned response can also be retrieved from the request object. To recap the process, read on:

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get"."newFile.txt".true);
oReq.send();
Copy the code
1-1 Request type

Requests generated through XMLHttpRequest can get data in two ways, asynchronous or synchronous. The type of request is determined by the value of async, the third argument to the open() method of the XMLHttpRequest object. If the value of this parameter is false, the XMLHttpRequest request is made in synchronous mode, otherwise the process is completed in asynchronous mode.

Note: Synchronization requests on the main thread have been deprecated starting with Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27) due to poor user experience.

1-2 Processing response

The W3C specification defines several types of response properties for an XMLHttpRequest object. These properties tell the client important information about the state of the XMLHttpRequest return. Some use cases dealing with non-text return types may include some of the operations and analysis described in the following sections.

Analyze and operate the responseXML property

If you use XMLHttpRequest to retrieve the contents of a remote XML document, the responseXML property will be a DOM object parsed from the XML document, which is difficult to manipulate and parse. There are five main ways to analyze XML documents:

  • 1. Use XPath to locate the specified part of the document.
  • 2. Manually parse and serialize XML into strings or objects.
  • 3. Use XMLSerializer to serialize the DOM tree into a string or file.
  • 4. If you know the contents of an XML document in advance, you can use RegExp. If you are affected by line breaks when scanning with RegExp, you may want to remove all line breaks. However, this approach is a “last resort” because it may fail if the XML code changes slightly.

1-2-2, parse and manipulate the responseText property containing the HTML document

If an HTML page is retrieved from a remote end using XMLHttpRequest, all the HTML tags are stored as strings in the responseText property, making it difficult to manipulate and parse the tags. There are three main ways to parse these HTML tags:

  • 1. UseXMLHttpRequest.responseXMLProperties.
  • 2. Pass the contentfragment.body.innerHTMLInject into a document fragment and iterate over the fragment in the DOM.
  • 3. If you know the contents of an HTML document in advance, you can use itRegExp. If you are affected by line breaks when scanning with RegExp, you may want to remove all line breaks. However, this approach is a “last resort” because it may fail if the HTML code changes slightly.
1-3 Processing binary data

Although XMLHttpRequest is generally used to send and receive text data, you can actually send and receive binary content as well. There are many well-tested ways to force the sending of binary data using XMLHttpRequest. Using XMLHttpRequest. OverrideMimeType () method is a solution, although it is not a standard method.

var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
// retrieve data unprocessed as a binary string
oReq.overrideMimeType("text/plain; charset=x-user-defined");
Copy the code

The responseType property has been added to the XMLHttpRequest Level 2 specification, making it easier to send and receive binary data.

var oReq = new XMLHttpRequest();

oReq.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  / *... * /
}
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.send();
Copy the code
1-4 Monitor progress

XMLHttpRequest provides various events that occur during the request being processed for listening. This includes periodic progress notifications, error notifications, and so on.

Dom-enabled progress event monitoring for XMLHttpRequest transport follows the Web API progress event specification: these events implement the ProgressEvent interface.

1-5 Submit forms and upload files

An instance of XMLHttpRequest can submit a form in two ways:

  • Using AJAX
  • Use the FormData API

The second method (using the FormData API) is the simplest and fastest, but the disadvantage is that the collected data cannot be converted to a JSON string using json.stringify (). The first approach is the most complex but also the most flexible and powerful.

Request here do not do too much redundant, a portal, interested partners can go to check.

Second, the Jquery Ajax

$.ajax({
  url: "/api/getWeather".data: {
    zipcode: 97201
  },
  success: function( result ) {$("#weather-temp" ).html( "<strong>" + result + "</strong> degrees"); }});Copy the code

Traditional Ajax refers to XMLHttpRequest (XHR), the earliest technology to send back-end requests, which belongs to the original JS. The core uses XMLHttpRequest objects. If multiple requests are sequential, callback hell can occur. Jquery Ajax has been updated and maintained for many years. However, with the rise of the react, Vue, Angular frameworks and the improvement of the ES specification, Jquery Ajax is very convenient. More API updates, which gradually reveal its shortcomings:

  • 1. The programming itself is for MVC, not in line with the current tide of front-end MVVM
  • 2. Based on native XHR development, the architecture of XHR itself is not clear, and fetch has been replaced
  • 3. The whole JQuery project is too large, and it is unreasonable to introduce the whole JQuery using Ajax alone (personalized package scheme can not enjoy CDN service)
  • 4. It does not conform to the principle of Separation of Concerns
  • 5. Configuration and invocation are messy, and the event-based asynchronous model is unfriendly

By default, Ajax requests use the GET method. If you want to use the POST method, you can set the type parameter value. This option also affects how the content in the Data option is sent to the server.

The data option can contain either a query string, such as key1=value1&key2=value2, or a mapping, such as {key1: ‘value1’, key2: ‘value2’}. If the latter form is used, the data resender is converted to a query string. This process can also be circumvented by setting the processData option to false. This might not be appropriate if we want to send an XML object to the server. And in this case, we should also change the value of the contentType option, replacing the default Application/X-www-form-urlencoded with another suitable MIME type.

var list = {}; 
$.ajax({
    / / request method POST | | the GET
    type : "POST".// The type of media requested
    contentType: "application/json; charset=UTF-8".// Request an address
    url : "http://127.0.0.1/xxxx/".// Data, json string
    data : JSON.stringify(list),
    // The request succeeded
    success : function(result) {
        console.log(result);
    },
    // The request failed, containing specific error information
    error : function(e){
        console.log(e.status);
        console.log(e.responseText); }});Copy the code

The following table lists jQuery AJAX methods:

methods describe
$.ajax() Perform asynchronous AJAX requests
$.ajaxPrefilter() Before each request is sent and by$.ajax()Before processing, handle customizationsAjaxOption or modify an existing option
$.ajaxSetup() For futureAJAXRequest to set default values
$.ajaxTransport() Create objects that handle the actual transfer of Ajax data
$.get() Using AJAXHTTP GETRequest to load data from the server
$.getJSON() useHTTP GETRequest to load JSON-encoded data from the server
$.getScript() An HTTP GET request using AJAX loads and executes JavaScript from the server
$.param() Creates serialization of arrays or objectsRepresentation (URL query string that can be used for AJAX requests)
$.post() An HTTP POST request using AJAX loads data from the server
ajaxComplete() Specifying AJAX requestsRun on completionThe function of
ajaxError() Specifying AJAX requestsRun on failureThe function of
ajaxSend() Specifying AJAX requestsRun before sendingThe function of
ajaxStart() Specify the first AJAX requestRun at startThe function of
ajaxStop() Specify all AJAX requestsRun on completionThe function of
ajaxSuccess() Specifying AJAX requestsRun on successful completionThe function of
load() Loads data from the server and places the returned data in the specified element
serialize() The set of encoding form elements isstringIn order to submit
serializeArray() The set of encoding form elements isnamesvaluesAn array of

I’m a big fan of Jquery Ajax, but as people move on, new knowledge will eventually replace the old.

Summary: Here is a quote from White Beard, the king of One Piece, as shown in the picture, don’t look at it until it comes out

Third, Axios

Let’s take a look at the case on the official website:

Performing a GET request

// Create a request for the user with the given ID
axios.get('/user? ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// The above request can also do the same
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code

Performing a POST request

axios.post('/user', {
    firstName: 'Fred'.lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code

Execute multiple concurrent requests

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now completed
  }));
Copy the code

After Vue2.0, You Yuxi recommended that you replace JQuery ajax with Axios. The trend of future apps is to be lightweight and refined. An application that can solve problems is a good application, and AXIos must have attracted many people’s attention. Axios is essentially a wrapper around the native XHR, but it’s an implementation version of Promise, available in browsers and Node.js, compliant with the latest ES specification, and has the following features on its website:

  • Create XMLHttpRequests from the browser
  • Create HTTP requests from Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF defense

XSRF (Cross Site Request Forgery), also known as XSRF, is a network attack mode. It was listed as one of the Top 20 Security risks on the Internet in 2007. Other security risks, such as SQL script injection and cross-site scripting attacks, have become well known in recent years, and many websites have taken precautions against them. However, CSRF is still a foreign concept to most people. Even Gmail, as well known, had a CSRF vulnerability at the end of 2007, which caused huge losses to Gmail users. The client supports XSRF defense. How to do this is to make every request you make carry a key from the cookie. According to the browser’s same-origin policy, the fake website cannot get the key from your cookie. To adopt the right strategy.

Configuration options that axios can use to create requests. Only urls are required. If method is not specified, the request uses the get method by default. Request to configure the portal

Axios, with its concurrent encapsulation, smaller size and none of the fetch issues I’ll discuss later, is the most desirable way to request now.

Fourth, the Fetch

Fetch provides a generic definition of Request and Response (and other objects related to network requests). Fetch is a modern concept, equivalent to XMLHttpRequest. It provides much of the same functionality as XMLHttpRequest, but is designed to be more extensible and efficient.

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.

Note that the FETCH specification differs from jquery.Ajax () in two main ways, keep in mind:

  • Returned from fetch() when an HTTP status code representing an error is receivedPromiseWill not be marked asrejectEven if the status code of the HTTP response is404500. Instead, it willPromiseThe status is marked asresolveHowever, the OK attribute of the return value of Resolve is set to false) is flagged only when the network fails or the request is blockedreject.
  • By default,fetchNothing is sent or received from the servercookiesIf the site depends on userssession, causes an unauthenticated request to be sentcookies, must be setcredentialsOption). After August 25, 2017, the default credentials policy has changed tosame-originFirefoxAlso change the default in 61.0b13

A basic FETCH request is simple to set up. Look at the following code:

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

Here we get a JSON file over the network and print it to the console. The simplest usage is to provide only one parameter to indicate the resource path to which you want to fetch(), and then return a Promise (a Response object) containing the Response result.

Of course, it’s just an HTTP response, not real JSON. To get the content of JSON, we need to use the JSON () method (defined in Bodymixin and implemented by the Request and Response objects).

Fetch () takes a second optional argument, an init object that can control different configurations:

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data= > console.log(data)) // JSON from `response.json()` call
  .catch(error= > console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache'.// *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin'.// include, same-origin, *omit
    headers: {
      'user-agent': 'the Mozilla / 4.0 MDN Example'.'content-type': 'application/json'
    },
    method: 'POST'.// *GET, POST, PUT, DELETE, etc.
    mode: 'cors'.// no-cors, cors, *same-origin
    redirect: 'follow'.// manual, *follow, error
    referrer: 'no-referrer'.// *client, no-referrer
  })
  .then(response= > response.json()) // parses response to JSON
}
Copy the code

Advantages of Fetch:

  • 1. Concise syntax and more semantic
  • 2. Support async/await based on standard Promise implementation
  • 3. Isomorphic-fetch is convenient for isomorphism
  • 4. More low-level, rich API (Request, response)
  • 5. Divorced from XHR, is a new implementation in ES specification

fetchThere’s one thing about front-end applications that XHR can’t match: cross-domain processing

We all know that because of the same-origin policy, browser requests can cross domains at will — you must have a cross-domain header or use JSONP. However, the fetch can set mode to “no-cors”, as shown below:

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

After that we get a return of type “opaque”. Need to point out that this request is really after arrived in Taiwan, so we can use this method to report information, before we image. The SRC method in a more choice, in addition, we can see the request in the network background Settings cross-domain head after the actual return, will help us to debug interface (of course, We can also do this via chrome.

See Fetch_API

See MDC AJAX Introduction

Reference source: MDN