One-sentence principle

The browser uses the XMLHttpRequest object to fetch resources from the server

Request step

1. Create an instance of the XMLHttpRequest request object

2. The callback function is registered successfully

3. Set request parameters and establish a connection to the server

4. Send a request to the server

code

var xhr = new XMLHttpRequest() xhr.onreadystatechange = function(){ if(this.readyState==4){ console.log(xhr.responseText) } } xhr.open('get','url',true); xhr.send(); // A POST request requires the HTTP request header to be set and the parameters to be sentCopy the code

ReadyState five states

    0- (uninitialized) The send() method has not been called yet1- (load) The send() method has been called and the request is being sent2- (Load complete) The send() method is completed and all responses have been received3- (Interaction) Parsing the response content4- (Done) The response content is parsed and can be invoked on the clientCopy the code

benefits

  • Speed up: Lighten the load on the server, load data on demand, minimize the number of requests

  • Improved user experience: Partial page refresh reduces user wait time and brings better user experience

  • Separation of pages and data: separation of front and back ends, more flexible operation of each end, more convenient maintenance