1. Introduction of AJAX

1.1 What is AJAX

Ajax full spell for async javascript and XML asynchronous JS and XML

1.2 XML (Extensible Markup Language)

Is used to store data (clearly display the data structure with its own extended tag name)

The main reason why Ajax became asynchronous JS and XML is that when ajax was first used to realize data communication between client and server, the data format was generally XML format, which we called asynchronous JS and XML (now data transmission is generally based on JSON format).

For example, the data format is as follows


      
<root>
    <student>
        <name>Zhang SAN</name>
        <age>25</age>
            <score>
                <english>90</english>
                <math>100</math>
                <chinese>97</chinese>
            </score>
       </student>
      <student>
        <name>Zhang SAN</name>
         <age>25</age>
            <score>
                <english>90</english>
                <math>100</math>
                <chinese>97</chinese>
            </score>
      </student>
</root>
Copy the code

1.3 Asynchronous JS

Asynchronous here doesn’t mean that Ajax can only make requests based on asynchrony (although asynchronous programming is recommended for all), asynchronous here means local refresh

2 The front and rear ends are separated

The fuse that separates the front and rear ends is global refresh and local refresh

2.1 Global Refresh (Not Separated from the Front and Back Ends)

Global refresh: When only one part of the page needs to be changed, the server needs to render the whole page, and finally the client browser refreshes the whole page to see the effect

  • In a project that is not completely separated from the front and back ends, the front-end development only needs to complete the production of the page, and some basic human-computer interaction effects can be completed with JS
  • The parts of the page that need to be rendered dynamically are left to the back-end developers to do data binding and server-based rendering (server rendering).

advantage

  1. Dynamic warrior data in the page of the source code courseware, conducive to SEO optimization promotion (conducive to search engine collection and crawl)
  2. The result obtained from the server side is already the final result to be presented, there is no need for the client to do additional things, so the page loading speed is fast (the premise is that the server side processing speed is fast enough), so similar to jd.com, Taobao such websites, the first screen data is generally rendered by the server side

disadvantage

  1. If the page has data that needs to be updated in real time, and the page has to be refreshed every time it wants to display the latest data, it will not work
  2. The server side to do data rendering, server side pressure, if the server can not handle, the speed of the page will be slower
  3. This model is not conducive to development (low development efficiency)

2.2 Local Refresh (Separated from the Front and Rear Ends)

The front and back ends of the project are completely separated, and the data in the page that needs to be dynamically bound is handed over to the client to complete rendering

process

  1. Send an AJAX request to the server
  2. The data obtained from the server side is parsed and processed to concatenate into the HTML strings we need
  3. The concatenated string to replace a part of the page content (local refresh), the whole page does not need to reload, local rendering

advantage

  1. We can arbitrarily modify the content of a certain part of the page (such as real-time refresh) according to the needs, the overall page does not refresh, good performance, good experience (all form validation, need to implement the refresh needs to be local AJAX implementation)
  2. It is beneficial to development and improve development efficiency
    • The separation of the front and back ends, the back end does not need to consider how the front end is presented, and the front end does not need to consider what technology is used in the back end, in the true sense of technology division is realized
    • Simultaneous development: At the beginning of project development, the interface document for data interaction between the front and back ends is specified (the document contains the protocol specification for retrieving the interface or the data), and the interface is written in the background (currently, many companies also need the front-end to simulate these interfaces with NODE

disadvantages

  1. Not conducive to SEO optimization: The content obtained from the server for the first time does not contain data that needs dynamic binding, so the source code of the page does not contain these contents, which is not conducive to SEO. The content added to the page through JS in the later period will not uninstall the source code of the page (is the source code not the page structure).
  2. When rendered by the client, the page first needs to be rendered, and then the data is obtained through JS’s asynchronous AJAX request, and then the data binding. The browser rerenders the added part of dynamic data, which wastes some time and is not as fast as the page rendering speed of server side rendering

3 Details of AJAX parameters

3.1 Creating an AJAX object

steps

  1. Creating AJAX objects
  2. Open request address
  3. Listen for AJAX state changes to get information
  4. Sending An AJAX request

The following code

// Create the AJAX object
let xhr = new XMLHttpRequest(); // Incompatible with Internet Explorer 6 and later (IE6: ActiveXObject)

// Open request address (understood as some basic configuration, but did not send the request)
xhr.open([method],[url],[async],[user_name],[user_password]);
// Listen for AJAX state changes and get the corresponding information (get the response header, get the response body)
xhr.onreadystatechange=() = >{
    if(xhr.readyState === 4 && xhr.status === 200) {let result = xhr.responseText;// Get the content in the corresponding topic}}// Send the AJAX request (the content in parentheses is the subject content of the request)
xhr.send(null);
Copy the code

3.2 Setting (open) Parameters

xhr.open([method],[url],[async],[user_name],[user_password])

3.2.1 [Method] Request parameters

Request way

  • GET series of requests
    • Get: Obtains data from the server
    • Delete: Deletes some data from the server
  • POST Request Mode
    • Post: Data is submitted
    • Put: adds or subtracts specified data to the server
  • Either way, the client can pass the information to the server, and the server can return the information to the client
  • GET series are usually based on getting (give less, take more)
  • POST series are generally push oriented (give more, take less)

GET VS POST

  • GET requests generally don’t pass as much content to the server as POST requests
    • Reason: GET requests to the server are generally based on contentThe url address question mark is passedPOST requests are generallySet request body basedTo achieve. Each browser has its own maximum URL length limit (Google: 8K, Firefox: 7K, IE: 2K). If the URL exceeds the limit, the browser will automatically intercept the URL, resulting in the loss of data to the server. In theory, there is no limit to the size of POST requests sent through the body. In real projects, we also limit the size of POST requests to ensure the transfer rate (for example, we do size limits for uploaded data or images).
  • GET requests are likely to appear in your cache (this cache is out of control: we don’t normally need it), while POST requests are not cached (unless you do something special).
setTimeout(() = >{
    $.ajax({
    url:'getList? lx=news'. success=>{// After the first request, the browser sends a second request.
        // But when you send a new request, both the address and the parameters are the same as the last one
        // The browser is more likely to fetch the last data instead of the latest data}},60000);
})
Copy the code
  • Solution: Each time a request is made, a random number is appended to the end of the URL to ensure that the address of each request is not exactly the same, so you can avoid reading data from the cache
setTimeout(()=>{ $.ajax({ url:'getList? lx=news&_='+Math.random(), ... success=>{ } },60000); })Copy the code
  • GET requests are not as secure as POST requests (POST is not very secure either, but relatively secure)
    • Reason: because GET is the URL passed to the server (there is a relatively simple hacking technique: URL hijacking, that is, the client can pass the data to the server hijacked, resulting in information leakage)

3.2.2 [URL] Indicates the request address

Request address of backend interface (API interface)

3.2.3 async asynchronous

  • ASYNC asynchronous
  • SYNC SYNC
  • Sets whether the current AJAX request is asynchronous or synchronous. Default is asynchronous (TRUE).
  • If set to FALSE, it represents synchronization at the current request

3.2.4 [user_name],[user_password] Specifies the user name and password

  • These two parameters are generally not used
  • If the server where the REQUESTED URL is located has set the access permission, we need to provide the user name and password that can communicate with each other (generally, the server can allow anonymous access).

3.3 AJAX status code

Xhr. readyState that describes the state of the current AJAX operation

  • 0 :UNSENT, which defaults to 0 whenever an AJAX object is created
  • 1 :HEADERS_RECEIVED The current AJAX request has been sent and the response header returned by the server has been received
  • 3 :LOADING The response body is on the way back
  • 4 :DONE The response body has been returned to the client

3.4 HTTP Network Status

HTTP network status code: records the status returned by the current server (xhr.status)

200: Success, a complete HTTP transaction completed (status codes starting with 2 are generally successful)

The ones that start with 3 are generally successful, but the server does special processing

301:Moved Permanently

(Task 307 is temporary redirection in the new HTTP version.) This operation is used for server load balancing. The current server cannot handle the current request, so we temporarily return the request to another server.

Cache files or content that is Not updated frequently to the browser and retrieve it from the cache the next time, reducing server stress and speeding up page loading

Generally, the first 4 is a failure, and the browser problem is large

400: The request parameter is incorrect

401: No access permission

404: The access address does not exist

The ones starting with 5 are usually failures, and the server problems tend to be large

500:Internal Server Error An unknown Server Error

503: Load on the Service Unavailable server

3.5 AJAX parameters and Methods

Run the following code to see the AJAX properties and methods

let xhr = new XMLHttpRequest();
dir(xhr)
Copy the code

The result is shown in figure

3.5.1 Related Properties

  • ReadState: Stores the current AJAX status code
  • response/responseText/responseXML: is used to accept the content in the response body returned by the server, but according to the server returned content format is different, we use different attributes to receive
    • responseTextIs the most common, and the content is received in a string format (usually the server returns data as a JSON string).
    • responseXMLOccasionally, if the server is returning XML document data, we need to use this attribute to receive it
  • Starus: Records the HTTP status code returned by the server
  • StatusText: Returns a description of the status code
  • Timeout: Set the timeout period for the current AJAX request. Suppose we set the timeout period to 3000 (MS). If the response body is not returned after 3 seconds, the browser will disconnect the current AJAX request task

3.5.2 Related methods

  • Abort () : Forces an AJAX request to break
  • GetAllResponseHeaders () : Gets the response header with the specified property name. For example, xhr.getresponseHeader (‘ date ‘) gets the server time stored in the response header
  • Open () : opens a URL
  • OverrideMimeType () : Overrides the MIME type of the data
  • Send () : Sends an AJAX request (the message in parentheses is that the client passes the information to the server based on the request body)
  • SetRequesHeader (key,value) : Set request header information (can be set custom request header)

3.5.3 Related Events

  • Onabort: This event is fired when an AJAX break occurs
  • Onreadystatechange: This event is triggered when the AJAX state changes
  • Ontimeout: This event is triggered when an AJAX request times out

3.5.4 Code Example

let xhr = new XMLHttpRequest();
xhr.open('get'.'url? _ = '+Math.random(),true);
// xhr.setrequesTheader ('cookie',' training ') sets that the request header content cannot appear in Chinese
// And header keys cannot be cookies
// The request header must be set after OPEN and before SEND
xhr.setRequestHeader('aaa'.'xxx');
// Set the request timeout period
xhr.timeout = 10;
// The method that is triggered when the request times out
xhr.ontimeout = () = >{
    console.log('Request has timed out');
    xhr.abort();
}
// This method is triggered when the request state changes
xhr.onreadystatechange=() = >{
    let {readyState:state,status}=xhr
    // If there is no return, it is successful
    if(!/^(2|3)\d{2}$)/.test(status)) return;
    // The response header is obtained when the state is 2
    if (state === 2) {let headerAll = xhr.getAllResponseHeaders(),
        New Date = new Date = new Date = new Date = new Date = new Date = new Date = new Date
        serverDate = xhr.getResponseHeader('data');
        console.log(headerAll,new Date(serverDate));
        return;
    }
     // The response body is already back when the status is 4
        if (state === 4) {// The result is usually a JSON string (which can be converted to a JSON object using json.parse).
        let valueText = xhr.responseText,
        // The result is the data in SML format (you can retrieve the stored information through some normal operations with XML)
        // If the server returns an XML document, responseText gets a string and responseXML gets a standard XML document
        valueXML = xhr.responseXML;
        console.log(valueText,valueXML);
        return; }}// Send the request
xhr.send('name=zxt&age=28&sex=man');
Copy the code

3.6 Detailed Explanation of AJAX Synchronization and Asynchronous

The difference between synchronous and asynchronous is whether an asynchronous parameter is added to xhr.open

3.6.1 synchronization

Compare the following two pieces of code

let xhr = new XMLHttpRequest();
xhr.open('get'.'temp.json'.false);
xhr.onreadystatechange = () = >{
    console.log(xhr.readyState);// Output the result only once
}
xhr.send(); 
Copy the code
let xhr = new XMLHttpRequest();
xhr.open('get'.'temp.json'.false);
xhr.send(); 
xhr.onreadystatechange = () = >{
    console.log(xhr.readyState); // Not once
}
Copy the code
  • Two pieces of codexhr.send();The position of the different causes the difference
  • The reason:
    • Start the AJAX request, start the AJAX task, nothing can be done until the task is complete, and nothing can be done with the binding event below
    • The state of the AJAX is no longer changed to any other value, so the event is never fired
  • With AJAX synchronous programming, don’t put SEND before the event listener, so we can’t get the response topic content in the bound method

3.6.1 asynchronous

Compare the following two pieces of code

let xhr = new XMLHttpRequest();
xhr.open('get'.'temp.json');
xhr.onreadystatechange = () = >{
    console.log(xhr.readyState);
}
xhr.send();
// the output is 2,3,4
Copy the code
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () = >{
    console.log(xhr.readyState);
    }
xhr.open('get'.'temp.json');
xhr.send();
// the output is 1,2,3,4
Copy the code
  • The difference between the two pieces of code is the location of xhr.onReadyStatechange
  • In the first code, open is set to asynchronous and you are not listening yet
  • By the time the listener’s state has changed to 2

JS commonly used in the compilation (solution) code method

4.1 Normal encoding and decoding

4.1.1 escape/unescape

  • Windows built-in methods
  • It mainly encodes and decodes Chinese characters
  • Generally only JS language support, but also often used in front-end page communication when Chinese coding problems
let str = 'training @ 163. com'
escape(str);
/ / show "% u57F9%[email protected]"
unescape('%u57F9%[email protected]')
// Display "[email protected]"
Copy the code

4.1.2 encodeURI/decodeURI

  • Windows built-in methods
  • To encode and decode Chinese characters
let str = 'training @ 163. com';
encodeURI(str); // "%E5%9F%B9%E8%AE%[email protected]"
decodeURI('%E5%9F%B9%E8%AE%[email protected]')// "training @163.com"
Copy the code

4.1.3 encodeURIComponent/encodeURIComponent

let str = 'training @ 163. com';
encodeURIComponent(str);// "%E5%9F%B9%E8%AE%AD%40163.com"
encodeURIComponent('%E5%9F%B9%E8%AE%AD%40163.com');// "training @163.com"
Copy the code

4.1.4 encodeURI Difference encodeURIComponent

  1. EncodeURI does not handle the special character \
  2. EncodeURIComponent handles special characters \
  3. When we pass a parameter in the URL question mark, the parameter we pass is still a URL or contains many special characters. In this case, we need to encode the parameter value in order not to affect the main URL. EncodeURI cannot encode some special characters, soOnly encodeURIComponent can be used

4.2 Encryption mode Encoding and decoding

  1. Reversible encryption (usually team defined rules)
  2. Irreversible encryption (generally based on MD5 encryption)
  3. MD5 encryption is irreversible. The encryption that is commonly used can be parsed by matching big data on the Internet. The encryption that is not commonly used cannot be parsed

Implementation of AJAX

5.1 AJAX in Jquery

$.ajax({
    url:'xxxx'.// The requested API address
    method:'get'.// Request mode GET/POST. In the older version, we used type and we used method to achieve the same effect
    dataType:'json'.// dataType knowledge we default to get the result type, does not affect the server return
    // (The server usually returns a STRING in JSON format), if the default is JSON, then the library will convert the string returned by the server into a JSON object
    // If we default to text (the default), we can just take the result from the server, we can also default to XML, etc
    cache:false.// Set whether to clear the cache, only for GET series requests. The default is TRUE to not clear the cache, manually set to FALSE, JQ class library
    // A random number is appended to the end of the request URL to clear the cache
    data:null.// We can pass some information to the server through DATA; The GET series of requests concatenates the contents of DAT at the end of the URL,
    // POST series requests are passed to the server in the form of a question mark. The content of the POST series is passed to the server in the body of the request. The value of DATA can be set in one of two formats
    // String, object, if it is a string, what is set is passed to the server, if it is set to object,
    // JQ passes the object to the server as a string like XXX =xxx&xxx= XXX
    async:true.The default value is TRUE for asynchronous and FALSE for synchronous
    success:function() {
        // When the AJAX request succeeds (readyState===4&status starts with 2 or 3)
        // After the request succeeds, JQ executes the callback function and passes the result as an argument (result is the result we fetched from the server).
    },
    error:function() {
      // The request error triggers the callback function
    },
    complate:function() {
      // The callback function is fired whether the request is incorrect or correct.}})Copy the code

5.2 Manually Encapsulating AJAX

~function() { class ajaxClass{ init(){ let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () =>{ if(! /^[23]\d{2}$/.test(xhr.status)) return; if(xhr.readyState === 4){ let result = xhr.responseText; switch (this.dataType.toUpperCase()){ case 'TEXT': case 'HTML': break; case 'JSON': result = JSON.parse(result); case 'XML': result = xhr.responseXML; } this.success(result); }}; If (this.data! == null){ this.formatData(); if(this.isGet){ this.url += `${this.querySymbol()}`; }} // Whether to remove the cache this.isget? this.cacheFn():null; xhr.open(this.method,this.url,this.async); xhr.send(this.data); } formatData(){ if(Object.prototype.toString.call(this.data)==='[object,object]'){ let obj = this.data, str = ''; for(let key in obj){ if(obj.hasOwnProperty(key)){ str += `${key}=${obj[key]}&`; } } str = str.replace(/&$/g,'') this.data = str; }} cacheFn() {! this.cache? this.url += `${this.querySymbol()}_=${Math.random()}`:null; } // Check whether the end is? querySymbol(){ return this.url.indexOf('? ') > 1? '&' : '? '; } } window.ajax = function({ url = null, method = 'GET', type = 'GET', data = null, dataType = 'JSON', cache = true, async = true, success = null } = {}){ let example = new ajaxClass(); example.url = url; example.method = type === null? method:type; example.data = data; example.dataType = dataType; example.cache = cache; example.async = async; example.success = typeof success === 'function'? success: new Function(); example.isGet = /^(GET|DELETE|HEAD)$/i.test(example.method); example.init(); }} ();Copy the code