One article on Ajax principles is enough.

  css, Front end, html, javascript, Programmer

Preface

AJAX, or “Asynchronous Javascript And XML,” refers to a web page development technology that creates interactive web page applications. AJAX is a technology for creating fast dynamic web pages. It enables developers to only obtain data from servers (instead of images, HTML documents and other resources). The transmission of Internet resources has become unprecedented lightweight and pure. This has stimulated the creativity of the vast number of developers, and has caused various powerful network sites and Internet applications to spring up like bamboo shoots after a spring rain, constantly bringing surprises to people.

The starting address of this article isGitHub blog, writing articles is not easy, please support and pay more attention!

First, what is Ajax

Ajax is a web development technology that requests data asynchronously, which is very helpful to improve the user experience and page performance. Simply put, Ajax loads background data through asynchronous requests and renders it on the web page without refreshing the page again. Common application scenarios include whether the form was successfully registered, Baidu search drop-down box prompt and express order number query, etc.Ajax aims to improve user experience and reduce the amount of network data transmission.At the same time, because AJAX requests to obtain data instead of HTML documents, it also saves network bandwidth and makes the surfing experience of Internet users smoother.

Second, what is the Ajax principle

Before explaining the Ajax principle, we might as well give an example of “the leader wants to find Xiao Li to report his work”. if the leader wants to find Xiao Li to ask him something, he entrusts the secretary to call Xiao Li and then does other things until the secretary tells him Xiao Li has arrived and finally Xiao Li reports to the leader.

Ajax request data flow is similar to “the leader wants to find Xiao Li to report his work”. One of the core dependencies is the XMLHttpRequest object provided by the browser, which plays the role of a secretary, enabling the browser to issue HTTP requests and receive HTTP responses. The browser then does other things and renders the page after receiving the data returned by XHR.

After understanding how Ajax works, let’s discuss how to use Ajax.

Third, the use of Ajax

1. Create the Ajax core object XMLHttpRequest (remember to consider compatibility)

1. var xhr=null;
 2. if (window.XMLHttpRequest)
 3. {// compatible with IE7+,Firefox, Chrome, Opera, Safari
 4.   xhr=new XMLHttpRequest();
 5.} else{// compatible with IE6, IE5
 6.     xhr=new ActiveXObject("Microsoft.XMLHTTP");
 7.   }

2. Send a request to the server

1. xhr.open(method,url,async);
 2. send(string);  //Use string parameters only when //post requests, otherwise do not take parameters.
  • Method: type of request; GET or POST
  • Url: Location of File on Server
  • Async:true (asynchronous) or false (synchronous)

Note: post requests must be formatted with the request header

xhr.open("POST","test.html",true);
 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xhr.send("fname=Henry&lname=Ford");  //post request parameter is put in send, i.e. request body

3. Server Response Processing (Distinguish between Synchronous and Asynchronous)

ResponseText obtains response data in the form of a string.

ResponseXML obtains response data in XML form.

(1) synchronous processing

1. xhr.open("GET","info.txt",false);
 2. xhr.send();
 3. document.getElementById("myDiv").innerHTML=xhr.responseText;  //The acquired data is directly displayed on the page

② Asynchronous processing

It is relatively complicated and should be handled in the event of requesting a state change.

1. xhr.onreadystatechange=function()  {
 2.    if (xhr.readyState==4 &&xhr.status==200)  {
 3.       document.getElementById("myDiv").innerHTML=xhr.responseText;
 4.      }
 5.    }

What is readyState?

ReadyState is an attribute of the XMLHttpRequest object and is used to identify the current state of the XMLHttpRequest object.
ReadyState has a total of 5 state values, ranging from 0 to 4, each representing a different meaning.

  • 0: uninitialized-the. open () method has not been called;
  • 1: Start-The. open () method has been called, but the. send () method has not been called;
  • 2: send-The. send () method has been called but no response has been received;
  • 3: receiving-partial response data has been received;
  • 4: Complete-all response data have been received and can be used in the client.

What is status?

The HTTP status code consists of three decimal digits. The first decimal digit defines the type of status code. The latter two digits have no classification function. HTTP status codes are divided into 5 types:

Common status codes

There are 40 kinds of HTTP status codes recorded on RFC2616 alone. If WebDAV(RFC4918, 5842) and additional HTTP status codes (RFC6585) are added, the number will reach more than 60 kinds. Next, we will introduce some representative status codes.

  • 200 indicates that the request from the client is normally processed at the server.
  • 204 indicates that the request was processed successfully, but no resources were returned.
  • 301 indicates permanent redirection. This status code indicates that the requested resource has been assigned a new URI, and the URI the resource now refers to should be used in the future.
  • 302 indicates temporary redirection.
  • 304 indicates that when the client sends a request with conditions (it means that the request message using GET method contains any header of IF-MATCHE D, IF-MODIFIED-SINCE, IF-NONE-MATCH, IF-RANGE, IF-UNMODIFIED-SINCE), the server allows the request to access resources, but after the request fails to meet the conditions, it directly returns 304Modified (the server-side resources are unchanged, and the client’s unexpired cache can be directly used)
  • 400 indicates a syntax error in the request message. When an error occurs, the request needs to be modified and sent again.
  • 401 indicates Unauthorized, and the current request requires user authentication
  • 403 indicates that access to the requested resource was denied by the server
  • 404 indicates that the requested resource cannot be found on the server. In addition, it can also be used when the server rejects the request and does not want to explain the reason.
  • 500 indicates an error occurred at the server while executing the request. It may also be a bug or some temporary failure in the Web application.
  • 503 indicates that the server is temporarily overloaded or is undergoing downtime maintenance and cannot process the request at this time.

③ Difference between ③GET and POST request data

  • When using Get requests, the parameters are displayed in the URL, while when using Post, they are placed in send.
  • The amount of data sent by Get request is small, while the amount of data sent by Post request is large.
  • Requests that use Get are less secure and will be cached, whereas Post requests are not

For the first difference, see the following two pictures for details:

Iv. concluding remarks

In fact, network requests are made through XMLHttpRequest or the encapsulated framework. This method is a bit old and the configuration and calling methods are very confusing. Fetch, which has just come out in recent years, provides a better alternative method. It not only provides a simple and logical way to asynchronously obtain resources across the network, but also can be easily used by other technologies.

To find out how to use Fetch to request data, please stamp fiercely.
How does fetch request common data formats

To find out how Ajax requests background data, please jab
Ajax requests background data

Reference article

Javascript tutorial

Introduction to Ajax

Never learn AJAX again! (A) AJAX Overview

HTTP novice tutorial

The difference between AJAX POST and GET requests