Learn about AJAX and how AJAX sends requests

  due to the limited capability of JavaScript, the API s it provides only stay in the stand-alone stage. This will make some functions impossible to realize. For example, when the user logs in, the user will display the user's corresponding avatar when entering the user account; When the user registration cannot be realized, the user will be prompted whether the user exists when entering the account or user name; Unable to see the latest user messages on the message board.

  the common point of these problems is that the data is stored in the server and cannot be obtained through the known API. The emergence of Ajax solves these problems.

   the known way to send a request is to enter the address in the address bar, press enter to refresh, the href or src attribute of a specific element, the submission of a form, use ajax to send a network request directly through JavaScript, send a request to the server and accept the response returned by the server. In this way, the functions will be more, and it is no longer a stand-alone game.

At this point, the emergence of Ajax solves these problems

Ajax (Asynchronous JavaScript and XML) is a technical solution for web editing (sending request and receiving response) on the browser side. You can get the latest content of the server directly through JavaScript without reloading the page (local refresh).

   Ajax is a set of API s provided by the browser, which can be called through JavaScript, so as to control the request and response through code and realize network programming through JavaScript.
   it is usually used to automatically update the page content, locally refresh the page, verify user data, and obtain data on demand.

Here is a set of native Ajax sending request steps
//Steps to send an ajax request
  
 //1 create an object of type XMLHTTPRequest -- equivalent to opening a browser
// var xhr = new XMLHttpRequest();
// The following is the IE6 compatible writing method
var xhr = null;
if (window.XMLHttpRequest) {
      // Standard browser
       xhr = new XMLHttpRequest;
} else {
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }
// A status before the request is not sent ----- unsent--0
 console.log("UNSENT",xhr.readyState);

//2 open a connection with the web address - equivalent to entering the web address in the address bar
xhr.open("GET","https://jsonplaceholder.typicode.com/users");
//open (method, interface address url) method 
// Open the request get, post, put and delete to obtain, submit, change and delete
// The connection has just been opened, but the opened --- 1 has not been sent yet
console.log("OPENED", xhr.readyState);
// setRequestHeader() 
// Set request header
// xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//If it is a get method, there is no need to pass parameters in send or set the request header
//Because its parameters are written on the web address (there is no need to pass parameters in send)
// xhr.open("GET", "https://jsonplaceholder.typicocde.com/users?id=1");
//post
// xhr.open("POST","https://jsonplaceholder.typicocde.com/users");
// xhr.send("name=harry&age=19");
  
//3 send a request through a connection - equivalent to clicking enter or hyperlink
xhr.send("name=harry&age=19");
// Send (data body), when sending a request, when you need to send some data or write or change data to the database, you need to pass the data body
// The data body to be transferred should be transferred according to the type in the request header
// Therefore, before send ing and after open ing, you need to set a method --- setRequestHeader()
// As above;
  
//4 specify xhr state change event handling function --- equivalent to handling the operation after web page rendering
//Specify the callback function to process the obtained data
xhr.onreadystatechange = function(){
//Determine whether the request is completed by judging the readyState of xhr
if(this.readyState === 2){
      console.log("headers received",xhr.readyState);
      console.log(xhr.responseText)
}else if(this.readyState === 3){
       console.log("loading",xhr.readyState)
       console.log(xhr.responseText)
}else if(this.readyState === 4){
       console.log("done",xhr.readyState)
       console.log(xhr.responseText)
      }
}
To send an Ajax request:

① Create an object of type XMLHttpRequest

② Ready to send, open a connection to a web address

③ Execute send action

④ Specify xhr state change event handler

Among them, the XMLHttpRequest type object is the XMLHttpRequest type provided by the core of Ajax API, which is required for all Ajax operations.

​ var xhr = new XMLHttpRequest();
Or xhr = new ActiveXObject ("Microsoft.XMLHTTP"); (IE6 compatible)

In essence, XMLHttpRequest is the means by which JavaScript sends HTTP requests on the web platform, so the sent HTTP requests still conform to the format agreed by HTTP.

  • The open() method starts the request, XHR Open (request method. url)

    • The sending request methods are: get, post, delete, put

      • Get request is to obtain or query data. In get request, parameters are passed directly through '?' on the url Parameter transfer; There is no need to set the response body when making a get request.

      • Post request: in the post request, the request body is used to carry the data to be submitted, which is safer than the get request; The content type of the request header needs to be set for the post request to facilitate the server to receive data.

      • put request, update data request

      • delete request

    • xhr. The third parameter is whether the request is executed asynchronously. The default value is true, which means asynchronous, and false means synchronous execution. Synchronous execution is not recommended here, otherwise the code will get stuck in the send() step.

      [understanding of synchronization and asynchrony:

      • Synchronization means that when a person is doing one thing, he can only do one thing at a time. Only after finishing this can he do the next thing, and other things can only wait;

      • Asynchrony means that a person can do other things without waiting for the completion of one thing.]

    • The setrequestheader () method sets the request header. This method must be called between open () and send (). xhr.setRequestHeader(header,value);

      Of which:
         header is generally set to "content type", which is the data type to be transmitted by the server;

         value is the specific data type, commonly used "application/x-www-form-urlencode" and "application/json"“

  • The send () method sends a request, which is used to send an HTTP request, XHR Send (data body), which transmits parameters according to the type in the request header; If it is a get method, there is no need to set the data body. You can pass null or no parameters.

    [usually, in order to make sure that the event will be triggered, you must register readystatechange before sending the request send (), so that it can be triggered successfully whether synchronously or asynchronously]

  • The readyState property returns the current state of an XMLHTTPRequest agent. Since the readyStatechange event is triggered when the state of the xhr object changes, this event will be triggered multiple times. It has five different state values:

    readyStateState descriptionexplain
    0UNSENTxhr is created, but the open () method has not been called; (initialization)
    1OPENEDThe open () method is called to establish a connection; (establish connection)
    2HEADERS_RECEIVEDThe send () method is called to get the status line and response header; (response header received)
    3LOADINGIn the response body download, some data has been in responseText; (responder loading)
    4DONEAfter downloading the response body, you can directly use responseText; (loading completed)

    Generally, when the readyState value is 4, the subsequent logic of the response is executed, such as some event functions.
    xhr.onreadystatechange = function(){
      if(this.readyState == 4){
        / / subsequent logic
      }
    }

Keywords: Javascript Ajax

Added by jcoones on Fri, 18 Feb 2022 06:34:59 +0200