Ajax understanding and its application

1. Ajax full name: async JavaScript and xml

  • Asynchronous JavaScript and XML technologies.
  • It is a tool for the client to send messages to the server, and a tool for receiving responses.
  • It is a function of the default asynchronous execution mechanism.

2. Ajax core

  • XMLHttpRequest object.
  • Provided by browsers, developers can use it to make HTTP and HTTPS requests.
  • Without refreshing (resubmitting) the page, you can obtain the latest response from the server to modify the content of the page.

3. XMLHttpRequest attribute

1. onreadystatechange:

Used to specify the event handler that is triggered when the state changes.

xhr.onreadystatechange = function() {
           console.log("xhr.readystate")
        }
Copy Code

2. readyState:

Properties used to get the status of the request.

  • readyState===0: The initialization is not completed, and the open method has not been executed.
  • readyState===1: After the configuration information is completed, open is executed.
  • readyState===2: The send method has been executed.
  • readyState===3: Parsing the response content.
  • readyState===4: The content has been parsed and can be used on the client.

3. responseText

The user gets the corresponding properties of the server.

  • When the value of readyState is 0, 1, or 2, responseText is an empty string.
  • When the value of readyState is 3, responseText is the unfinished response information.
  • When the value of readyState is 4, responseText is the response information.

4. responseXML

It is used to describe the XML response when a complete HTTP response is received (when the readyState value is 4). If the readyState value is not 4, the value is null. If the response content type is “text/xml” or “application/xml”, this property will hold the XML DOM document of the corresponding data.

5.status

Attributes used to describe HTTP status codes. The status property is only available when readyState has a value of 3 or 4.

6. statusText

Code text used to describe the HTTP status. The statusText property is only available when readyState has a value of 3 or 4.

4.XMLHttpRequest object

1. open()

Used to set the URL of the asynchronous request, the request method and other parameter information

xhr.open('GET',"1.json",true);
        //The HTTP method of the first get post push delete request
        //Second request address
        //whether the third parameter is asynchronous
Copy Code

2. send()

Used to send requests to the server. If declared asynchronous, the method returns immediately, otherwise it waits until a response is received.

3. sendRequstHeader()

Used to set the value for the request’s HTTP header, this method must be used after the open() method call.

4. getRequstHeader()

Returns the specified HTTP header information as a string.

5. getAllRequstHeader()

Return the complete HTTP header information as a string.

5. Create an Ajax object

 //Create an ajax object
        var xhr = new XMLHttpRequest();
        xhr.open('GET',"1.json",true);
        //The first get post push delete
        //Second request address
        //whether the third parameter is asynchronous
        xhr. send();
        //Use send to send the request
Copy Code

For this, we set up a listener and write a callback function to specify the event handler triggered when the state changes, so that we can get the data returned by the server. If status===4, we can get the returned result. But if the backend returns an error, that is, the server status code is not between 200-299, we also need to know the error type it returns, so we can make a judgment.

One of the most basic ajax is the above three steps, only the above three steps. The request can be sent to the server. If the server is normal, the response can also be returned to the client, but we cannot get the returned data. If we want to get the response, there are two prerequisites:

  • 1. This HTTP request is successful, that is, the HTTP status code is 200-299.
  • 2. The ajax object has its own status code, which is used to represent the various stages in this ajax request.
 xhr.onreadystatechange = function() {
            // console. log("xhr. readystate")
        }
            if(xhr. readyState == 4){
                // It may not be the correct result, and then judge
                if(/^2\d{2}$/.test(xhr.status)){
              //Regular expression writing method, the judgment is equal to 200-299, all are normal.
                    console. log(JSON. parse(xhr. responseText))
                }else{
                console.log("error",xhr.responseText);
                // input error message
                }
            }
Copy Code

In this regard, we can observe that the above steps are too troublesome. It is necessary to judge the state of readyState before onload, so there is another method, namely onload

 xhr.onload = function(){
                if(/^2\d{2}$/.test(xhr.status)){
                    console. log(JSON. parse(xhr. responseText))
                }else{
                console.log("error",xhr.responseText);
                }
            }
        
Copy Code

This method can only go through once, which means that the data given to us by the backend has been loaded, and the step of judging readyState===4 is omitted, and only the status status is judged.

Server Status

  • 1xx

Indicates a provisional response and requires the requester to proceed.

  • 2xx

indicates success, and the common 200 indicates normal processing.

  • 3xx

Indicates further action required to complete the request, ie redirection.

  • 4xx

Client error, typically because the request contains syntax errors or cannot be completed.

  • 5xx

An internal error occurred while the server was trying to process the request. These errors came from the server itself, not from a bad request.

expand

common server status

  • 200 OK returns information normally;
  • 301 Moved Permanently The requested web page has been permanently moved to a new location;
  • 302 Found Temporary redirection
  • 306 Switch Proxy In the latest version of the specification, the 306 status code is no longer used
  • 403 Forbidden access prohibited;
  • 404 Not Found No resources found how to match the URI;
  • 405 Method Not Allowed The request method specified in the request line cannot be used to request the corresponding resource
  • 408 Request Timeout The request timed out.
  • 409 Conflict The request cannot be completed due to a conflict with the current state of the requested resource.
  • 410 Gone The requested resource is no longer available on the server and does not have any known forwarding addresses.
  • 500 Internal Server Error The most common server-side error;
  • 501 Not Implemented The server does not support a feature required by the current request. When the server does not recognize the requested method and cannot support its request for any resource.
  • 505 HTTP Version Not Supported The server does not support

HTTP method

Get

Use the Get method to obtain data, which is relatively simple, similar to the post() method, the difference between them is the data transfer. post() puts the requested data in the request body, so you need to call setRequestHeader() on the XHR object, but the Get method does not.

Post

Use the post method to add new data. Post is to put the requested data in the request body, so you need to call setRequestHeader() on the XHR object. Note! If you directly enter the following code, the new json will only display the id, because the code does not tell the server what format the data is in. requires attention.

 xhr.send({title:'newTitle',author:'newAuthor'});
Copy Code

Put

The modified data information can be directly represented by url + '\id', and the modified information can be seen after the database is refreshed successfully.

Delete

It should be noted that the modification information does not require the format of the data, because the data is gone, so comment the following code. Refresh the database again and you can see that the data in row 26 is gone.

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({title:'Modify',author:'xiaxia',age:'20'}));
Copy Code

Summary

Advantages of Ajax:

  • 1. No plug-in support is required, and native js is available.
  • 2. Good user experience (data can be updated without refreshing the page).
  • 3. Reduce the burden on the server and broadband.

Disadvantages of Ajax: The search engine support is not enough, because the data is not on the page, and the search engine cannot search it.

Note that the json-server xx.json command must be used to run the json file on the console before use.

In summary, the article is shared. My knowledge is shallow, and I really dare not compare with the big guys. I am working hard to learn. Welcome to point out the problems and make suggestions. Let’s work together to build a spring of computers.

Author: Cai Cai’s Xiaoxia
Link: https://juejin.cn/post/7212924329427927098
Source: Rare Earth Nuggets
Copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.