AJAX is what?

AJAX, Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that part of a web page can be updated without reloading the entire page. Traditional web pages (without Ajax) have to reload the entire page if they need to update content.

How AJAX works

Ajax works by adding an intermediate layer (the Ajax engine) between the user and the server, making user actions and server responses asynchronous. The client sends the request to XHR, XHR submits the request to the server, the server handles the business, the server sends the response data to XHR object, XHR object receives the data, and javascript writes the data to the page, as shown below:

Five steps of an AJAX request

1. Create the XMLHttpRequest object; 2. Set the callback function. 3. Configure request information (such as open and get methods) and use the open method to establish a link with the server. 4. Send data to the server. 5. Handle different response states in the callback function;Copy the code

1. Create an XMLHttpRequest asynchronous object

var xhr;  // Define a variable to hold the XMLHttpRequest object
if(window.XMLHttpRequest) { 
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xhr = new XMLHttpRequest();
} else {
  // code for IE6, IE5
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
Copy the code

2. Set the callback function

XHR. Onreadystatechange = callback;Copy the code

3. Use the open method to establish a connection to the server

/ / the get method
xhr.open("get"."test.php".true)

// To send data in POST mode, you need to set the request header
xhr.open("post"."test.php".true)
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded")
Copy the code

4. Send data to the server

// get does not need to pass arguments
xhr.send(null)

// Post needs to pass arguments
xhr.send("name=jay&age=18")
Copy the code

5. Handle different response states in the callback function

function callback() {
  // Determine the status of asynchronous objects
  if(xhr.readyState == 4) {
    // Determine if the interaction was successful
    if(xhr.status == 200) {
      // Get the data for the server response
      var res = xhr.responseText
      // Parse the data
      res = JSON.parse(res)
    }
  }
}
Copy the code
  • Five status codes in Ajax
    • 0: The request is not initialized
    • 1: Server connection established (open method called, but send not called)
    • 2: Request received (send method called)
    • 3: The request is being processed (the request has reached the server and is being processed)
    • 4: Request completed and response ready
    • Status: 200 — correct, 404 — page not found, 500 — error

A complete AJAX instance

// -----1. Create an XMLHttpRequest object, that is, create an asynchronous call object
var xhr = new XMLHttpRequest();
// -----3. Create a new HTTP request and specify the request method, URL, and authentication information
xhr.open('post'.'www.xxx.com'.true)
// Receive the return value
// -----2. Set the function to respond to changes in the HTTP request status ------5. The callback functions handle different states
xhr.onreadystatechange = function(){    //xhr.onreadystatechange = callback; Time the callback
  if(xhr.readyState === 4) {
    if(xhr.status >= 200 && xhr.status < 300 || CharacterData.status == 304) {
      console.log(xhr.responseText); }}}// ----- process request parameters
postData = {"name1": "value1"."name2": "value2"};
postData = (function(value){
  var dataString = "";
  for(var key in value){
       dataString += key+"="+value[key]+"&";
  };
    return dataString;
}(postData));

// Set the request header
xhr.setRequestHeader("Content-type"."applicationx-www-form-urlencoded");
// Exception handling
xhr.onerror = function() {
  console.log('Network request failed')}// Carry cookies across domains
xhr.withCredentials = true;
// ----4
xhr.send(postData);

Copy the code

References: Reference 1, Reference 2