1. How Ajax works

Ajax acts as a proxy for the browser to send requests and receive responses to improve the user experience by partially updating the page data without affecting the user’s ability to browse the page.

2. Ajax implementation steps

2.1. Create Ajax objects

var xhr = new XMLHttpRequest();
Copy the code

2.2. Tell Ajax where and how the request is made

xhr.open('get'.'http://www.example.com');
Copy the code

2.3. Send the request

xhr.send();
Copy the code

2.4. Obtain the response data from the server to the client

xhr.onload = function () {
    console.log(xhr.responseText);
}
Copy the code

3. Data format of the response from the server

In a real project, the server-side will most likely take JSON objects as the format for the response data. When the client gets the response data, it concatenates the JSON data with the HTML string and displays the concatenated result on the page.

In the process of HTTP request and response, both request parameters and response contents, if they are object types, will eventually be converted into object strings for transmission.

JSON.parse() // Convert json strings to JSON objects
Copy the code

4. Request parameter transfer

4.1. Traditional web site form submission

<form method="get" action="http://www.example.com">
    <input type="text" name="username"/>
    <input type="password" name="password">
</form><! - HTTP://www.example.com?username=zhangsan&password=123456 -->
Copy the code

4.2. GET Request mode

xhr.open('get'.'http://www.example.com?name=zhangsan&age=20');
Copy the code

4.3. POST Request mode

xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded') 
xhr.send('name=zhangsan&age=20');
Copy the code

5. Request packets

The blocks of data that are passed during HTTP requests and responses are called messages. They contain the data to be transmitted and additional information in a specified format.

6. Format of request parameters

6.1. Application/x – WWW – form – urlencoded

name=zhangsan&age=20& sex = maleCopy the code

6.2. application/json

{name: 'zhangsan'.age: '20'.sex: 'male'}
Copy the code

Specifying the content-Type attribute as application/ JSON in the request header tells the server that the current request parameter is in JSON format.

JSON.stringify() // Convert a JSON object to a JSON string
Copy the code

Note: GET requests cannot submit JSON object data format, and traditional web site form submission does not support JSON object data format.

7. Obtain the response from the server

7.1. Ajax status codes

Each step in the process of creating an Ajax object, configuring an Ajax object, sending the request, and receiving the server-side response data corresponds to a value called the Ajax status code.

  • 0: The request is not initialized (open() has not been called)
  • 1: The request has been established, but has not yet been sent (send() has not been called)
  • 2: The request has been sent
  • 3: The request is being processed, usually with some data already available in the response
  • 4: The response is complete, and the server’s response is ready to be retrieved and used

Xhr. readyState // Get the Ajax status code

7.2. The onreadystatechange event

This event is automatically triggered when the Ajax status code changes.

The Ajax status code can be retrieved and judged in the event handler, and when the status code is 4, the server response data can be retrieved via xhr.responseText.

// When the Ajax status code changes
xhr.onreadystatechange = function () {
    // Determine when the Ajax status code is 4
    if (xhr.readyState == 4) {
        // Get the response data from the server
        console.log(xhr.responseText); }}Copy the code

7.3. Differences between the two methods of obtaining server-side response

The difference between describing The onload event The onreadystatechange event
Whether it is compatible with earlier VERSIONS of IE Are not compatible Compatible with
Whether you need to determine the Ajax status code Don’t need Need to be
Number of calls At a time Many times

Ajax error handling

  1. The network is normal and the server can receive the request, but the result returned by the server is not the expected result.

You can judge the status code returned by the server and process it separately. Xhr. status Obtains the HTTP status code

  1. The server does not receive the request and returns the 404 status code.

Check if the requested address is incorrect.

  1. The network is smooth, the server can receive the request, and the server returns 500 status code.

Server side error, find back-end programmer to communicate.

  1. The network is interrupted, and the request cannot be sent to the server.

The onError event below the XHR object is raised, and the error is handled in the onError event handler.

9. The Cache of Internet Explorer of earlier versions is faulty

Problem: In earlier versions of Internet Explorer, Ajax requests have a serious caching problem, meaning that only the first request is actually sent to the server without changing the address of the request, and subsequent requests are retrieved from the browser’s cache. Even if the data on the server is updated, the client still gets the old data in the cache.

Solution: Add request parameters after the request address to ensure that the value of the request parameters is not the same in each request.

xhr.open('get'.'http://www.example.com?t=' + Math.random());
Copy the code