What is Ajax all about?

To put it simply, Ajax is for the client to send requests to the server.

In this era of separation between front and back ends, JS in our client side sends a request to the server side through Ajax, and obtains the content returned by the server, and finally renders the client side.

Why not just a normal HTTP request?

  • Ajax sends the request through the xmlHttpRequest object, and the server returns the data to update parts of the web page without reloading the entire page.
  • A normal HTTP request is sent through an httpRequest object, and the server returns the data to refresh the entire web page (one page for each HTTP request).

Ajax Native writing (JS)

  1. Create an object
var xhr = new XMLHttpRequest();
Copy the code
  1. Setting request parameters
xhr.open("GET"."/xxxx".true);
Copy the code
  1. Listening to the
xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {
      console.log('Request completed');
      if (xhr.status >= 200 && xhr.status < 300) {console.log('Request successful'); }}}Copy the code
  1. Send the request
xhr.send();
Copy the code
  1. Simplify the above steps
var xhr = new XMLHttpRequest();
xhr.open("GET"."/xxxx".true);
xhr.onlosd = () = >{ console.log('Request successful') }
xhr.send();
Copy the code

Libraries that encapsulate Ajax (for example, jquery.ajax)

$.get('/xxxx').then(function(response){
  // The response is the content returned
})
Copy the code

What formats of content can Ajax request?

  • The XML content
  • JSON content (most common)
  • HTML content
  • CSS content
  • JS content
  • .