preface

In the front-end development process, in addition to learning to use HTML + CSS to achieve some cool specific effects, there is an indispensable module worth our learning, that is the network request. In practice, we often use third-party libraries or frameworks (axios, jQuery, etc.) to send network requests for server data.

AJAX = Asynchronous Javascript And XML. It is a hybrid technology to get server data without page refresh. Ajax is actually a combination of these technologies: (1) presentation technology based on Web standard XHTML and CSS (2) dynamic display and interaction using DOM (Document ObjectModel) (3) data exchange and related operations using XML and XSLT (4) using XMLHttpRequest performs asynchronous data queries, retrieves, and (5) binds everything together using JavaScript

Admissions requirements

Before we dive further into Ajax, we need to understand a few concepts;

  1. Synchronous and asynchronous;
  2. What is XML;
  3. The difference between Get and Post requests;
  4. Ajax core XMLHTTPRequest;

Synchronous and asynchronous

Let’s take a look at an example of an AJAX request I saw earlier:

Asynchronous AJAX:

Main thread: “Hello, AJAX thread. Please send me an HTTP request and I will give you the address and parameters of the request.” AJAX threads: “Okay, main thread. I’ll do it right away, but it may take a while. You can do something else first.” Main thread: “Thanks, let me know when you get the response.” (The main thread then goes off to do something else, and after a while, it receives notification that the response has arrived.)

Synchronous AJAX:

Main thread: “Hello, AJAX thread. Please send me an HTTP request and I will give you the address and parameters of the request.” AJAX threads: “Okay, main thread. I’ll do it right away.” Main thread: “Hello, AJAX thread. Please send another HTTP request for me and I will give you the address and parameters of the request.” AJAX thread: “……” Main thread: “Hey, AJAX thread, why aren’t you talking?” AJAX thread: “……” Main thread: “Hello! Hey, hey!” AJAX thread: “……” Main thread: “Hello! Please say something!” AJAX thread: “Main thread, sorry, I can’t talk while I’m working. Your request has been sent. I got the response data. Here you go.”

From the above examples, we can see the difference between synchronous and asynchronous:

Synchronization means sending a request and then waiting to send the next request;

Asynchrony means sending a request without waiting for the next one.

The difference is that one has to wait and one doesn’t.

What is the XML

XML stands for Extensible Markup Language. It is a markup language, similar to HTML, in that XML tags are not predefined and need to be self-defined, but also have self-describing lines. It is mainly used to transfer and store data and is a W3C recommendation.

Examples of XML:

<bookstore> 
    <book category="COOKING"> 
        <title lang="en">A home cooking coup de grace</title> 
        <author>Zheng feng</author> 
        <year>2020</year> 
        <price>34.50</price> 
    </book> 
    <book category="CHILDREN">
        <title lang="en">Young people read historical records</title> 
        <author>Zhang Jiahua</author> 
        <year>2015</year> 
        <price>50</price> 
    </book> 
    <book category="WEB"> 
        <title lang="en">JavaScript advanced programming</title> 
        <author>Matt Frisby</author> 
        <year>2020</year> 
        <price>91</price> 
    </book>
</bookstore>
Copy the code

XML is commonly parsed in two ways, one is DOM parsing, the other is SAX parsing. DOM parsing is to read XML files at one time and generate tree structure. The advantage is convenient operation, but the disadvantage is that it consumes memory. SAX parsing is event-driven and takes up less memory, but it is complicated to program.

The difference between Get and Post requests

In fact, as Internet people, these two basic request way, should be more familiar. Although familiar, they will still be asked questions during the interview, and probably every candidate wants more answers.

Get requests include parameters in the URL, and Post requests pass parameters through the request body.

Get and Post are the two methods of sending HTTP requests. HTTP is a TCP/ IP-based hypertext transfer protocol, that is, the underlying layer of HTTP requests is TCP/IP, so Get and Post are TCP links.

The difference between

  1. Get requests do no harm when backward or refreshed, while Post resubmits requests.
  2. The address generated by a Get request can be set as a bookmark, whereas a Post cannot.
  3. Get requests are actively cached by browsers, whereas Post is not, unless set manually;
  4. Get requests can only be encoded by URL, while Post supports multiple encoding methods.
  5. Get request parameters are fully preserved in browser history, while parameters in Post are not.
  6. Get requests pass parameters in the URL that are limited in length (URL length is limited, maximum length is 2048 bytes), whereas Post does not.
  7. For Get requests, the data type of parameters can only be ASCII characters. For Post, there is no restriction, and binary data is allowed.
  8. Get requests are less secure because the data sent is part of the URL, while the parameters of Post are not saved in the browser or Web server logs.
  9. The data for a Get request is visible to everyone in the URL, while a Post is not displayed in the URL.
  10. When sending a Get request, the browser sends the Http Header and data together. The server responds with the data, generating a TCP packet. When sending a POST request, the browser sends the Http Header first, and the server responds with 100 continue, The browser sends data, and the server responds with 200 and returns data, generating two TCP packets.

XMLHTTPRequest

XMLHTTPRequest (XHR), first introduced in Internet Explorer 5, is a technology that supports asynchronous requests. It is mainly used to interact with servers. XHR allows users to request specific urls and obtain data without refreshing the page. This allows JavaScript to send requests and process responses to the server in a timely manner without blocking the user. It is also the core mechanism of Ajax.

XHR common object methods

  • abort()

    This method is primarily used to cancel the current request

  • getAllResponseHeaders()

    The main purpose of this method is to get header information

  • getResponseHeader()

    The main purpose of this method is to obtain a specified header information

  • open(method, url, async)

    This method is mainly used to specify the type of request, THE URL, and whether the request is processed asynchronously.

    Method Specifies the request type: Get or Post.

    Url request parameter indicates the request address;

    Async request parameter indicates synchronous asynchrony and its value is bool, true indicates asynchronous and false indicates synchronous.

  • send(string)

    This method is used to send requests to the server, and the request parameter string is used only for POST requests.

  • setRequestHeader(header, value)

    This method is used to add HTTP headers to the request. This method must be called between the open() and send() methods, and if the same request header is assigned multiple times, only one request header with multiple values is generated.

    The header argument represents the name of the header;

    The value argument represents the value of the header.

XHR Common object properties

  • timeout

    This property represents the maximum request time (milliseconds) beyond which the request is terminated automatically.

  • readyState

    This property represents the status code of the request.

    Common status codes are:

    • 0 indicates that the request is not initialized.
    • 1 The server link has been established and the open() method has been called. In this state, the request header can be set with the setRequestHeader() method, or the send() method can be called to send the request;
    • The request has been received, the send() method has been called, and the header and state are available;
    • If the responseType property is text or an empty string, the responseText will have part of the response data while loading.
    • 4 The request is complete and the response is ready.
  • onreadystatechange

    This property represents a callback method that is automatically called when the readyState property value changes.

    When an XHR request is canceled by abort(), the destroy method for this attribute is not fired.

    ⚠️⚠️⚠️ This property cannot be used to synchronize XHR objects. ⚠ ️ ⚠ ️ ⚠ ️

    Syntax: xhr. onreadyStatechange = callback;

  • responseText

    This property returns response data as a string, or NULL if the request was unsuccessful or not yet sent.

  • responseXML

    This property returns the response data as XML data, or NULL if the request is not sent or successful, and the unreturned data cannot be parsed into XML or HTML.

  • status

    This property returns the numeric status code in the response, with a value of 0 before the request completes or when an XHR error occurs. Common status codes include 200, 401, and 404.

  • statusText

    This property represents the status text returned in the response, which contains the numeric status code and the corresponding text information. For example: “200 OK” and so on. The value of this attribute is an empty string when the request status codes are 0 and 1.

Ajax

The working principle of

Ajax works by adding an intermediate layer between the user and the server to asynchronize the user’s actions and the server’s responses. In simple terms, it sends a web request to the server via an XMLHTTPRequest object to retrieve the server’s response data. The DOM is then manipulated via JavaScript to update the page without affecting the user’s other operations.

Common usage

Use Ajax in native JavaScript

  1. Create an XMLHttpRequest object;
var xhr = new XMLHttpRequest()
Copy the code
  1. Set the request mode, the address of the request, and whether the request is executed asynchronously.
/ / / Get request
xhr.open('get'.'/news/getNewsPage? pageNumber=' + pageNumber + 'pageSize' + pageSize , true)

/ / / Post request
xhr.open('post'.'/news/getNewsPage'.true)
Copy the code
  1. Set the request header;
/// Get request, request header can not be set
---------------
/// Post request, need to be set
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
Copy the code
  1. Send a request to the server;
/ / / Get request
xhr.send()

/ / / Post request
xhr.send('pageNumber=1&pageSize=20')
Copy the code
  1. Process server response data;
This attribute callback method is valid only when the XMLHttpRequest object is set to asynchronous and the request is not abort(). Refer to the previous chapter for details
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var res = JSON.parse(xhr.responseText)
        console.log(res)
    }
}
Copy the code

Use Ajax in jQuery

$. Ajax ({type: "get", / / / request url: "', / / / request address data: {}, / / / request parameter dataType: 'json, beforeSend: Function (XHR) {function (XHR) {function (res) {function (XHR) {error: Function (XHR, error) {}, complete: function () {}})Copy the code

summary

  1. Ajax is a web development technology for creating interactive web applications. The biggest characteristic of Ajax is that it can change the page content without refreshing.

  2. Ajax has the following advantages:

  • Improved user experience through asynchronous mode;

  • Optimized transmission between browser and server, reduce unnecessary data round-trip, reduce bandwidth consumption;

  • The Ajax engine operates on the client side, taking over some of the work that would otherwise be done by the server, thus reducing the load on the server under a large number of users.