preface

AJAX, Asynchronous Javascript And XML, refers to a web development technique for creating interactive web applications. AJAX is a technique for creating fast, dynamic web pages. It can make the developers only to get the data from the server (rather than images, HTML documents and other resources), the resources of the Internet transmission become unprecedented lightweight and pure, it inspired the majority of developers creativity, make all kinds of powerful web sites, and Internet applications have mushroomed in general, continuously to surprise people.

The first address of this article is GitHub blog, writing an article is not easy, please support and pay attention to!

What is Ajax

Ajax is a Web development technique that asynchronously requests data, which can help improve user experience and page performance. Simply put, Ajax loads background data through asynchronous requests and renders it on a web page without the need to refresh the page. Common application scenarios include form verification whether login is successful, Baidu search drop-down box prompt and express tracking number query, etc. Ajax is designed to improve the user experience and reduce the amount of data transferred over the network. ** Also, because AJAX requests fetch data rather than HTML documents, it saves network bandwidth and makes the web surfing experience smoother for Internet users.

What is the principle of Ajax

Before explaining the principle of Ajax, we might as well take the example of “the leader wants to report to Xiao Li”. The leader wants to ask something to Xiao Li, so he entrusts his secretary to call Xiao Li and then does other things until the secretary tells him that Xiao Li has arrived. Finally, Xiao Li reports to the leader.

The Ajax request data flow is similar to “the leader wants to talk to Xiao Li about his work.” The most central of these dependencies is the XMLHttpRequest object provided by the browser, which acts as a secretary, allowing the browser to make HTTP requests and receive HTTP responses. The browser then does other things and waits for the data to come back from XHR before rendering the page.

Now that you understand how Ajax works, let’s take a look at how to use Ajax.

The use of Ajax

1. Create the Core Ajax object XMLHttpRequest(remember compatibility)

	1. var xhr=null;  
	2. if{// Compatible with IE7+, Firefox, Chrome, Opera, Safari 4. XHR =new XMLHttpRequest(); 5.}else6. XHR =new ActiveXObject("Microsoft.XMLHTTP"); 7.}Copy the code

2. Send a request to the server

1. xhr.open(method,url,async); 2. send(string); // Only string arguments are used in post requests. Otherwise, no arguments are required.Copy the code
  • Method: Request type. GET or POST

  • Url: The location of the file on the server

  • Async: true or false Note: POST requests must set the format content of 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 parameters are placed in send, i.e. the request bodyCopy the code

3. Server response processing (distinguish synchronous and asynchronous cases)

ResponseText gets the response data as a string.

ResponseXML gets the response data in XML form.

① Synchronous processing

	1. xhr.open("GET"."info.txt".false);  
	2. xhr.send();  
	3. document.getElementById("myDiv").innerHTML=xhr.responseText; // Get data to display directly on the pageCopy the code

② Asynchronous processing

It is relatively complex to handle in a request state change event.

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

What is readyState?

ReadyState is an attribute of the XMLHttpRequest object that identifies the current state of the XMLHttpRequest object. ReadyState has five status values ranging from 0 to 4, each of which has 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;
  • 2: send — the.send() method has been called, but no response has been received;
  • 3: Receive: some response data has been received.
  • 4: Completed — all response data has been received and is ready for use on the client.

What is status?

The HTTP status code consists of three decimal digits. The first decimal digit defines the type of the status code, and the second two digits do not classify. HTTP status codes are classified into five types:

Common status codes

There are 40 types of HTTP status codes recorded in RFC2616 alone, and more than 60 types if WebDAV (RFC4918, 5842) and additional HTTP status codes (RFC6585) are added. Next, let’s take a look at some of these representative status codes.

  • 200 indicates that the request from the client is processed on the server.
  • 204 indicates that the request was processed successfully, but no resources were returned.
  • 301 indicates a permanent redirect. This status code indicates that the requested resource has been assigned a new URI and that the URI to which the resource now refers should be used later.
  • 302 represents a temporary redirect.
  • 304 When the client sends a conditional request (the request message using the GET method contains if-matched,if-modified-since,if-none-match,if-range, and if-unmodified-since headers), the server allows the request to access the information Source, but returns 304Modified because the request does not meet the condition.
  • 400 indicates that syntax errors exist in the request packet. When an error occurs, you need to modify the content of the request and send the request again.
  • 401 indicates that the request is Unauthorized and requires user authentication
  • 403 indicates that access to the requested resource was denied by the server
  • 404: The requested resource could not be found on the server. In addition, it can be used when the server rejects the request without giving a reason.
  • 500 indicates that an error occurred on the server side while executing the request. It could also be a Web application bug or some temporary glitch.
  • 503 indicates that the server is temporarily overloaded or is down for maintenance and is unable to process requests.

③ Differences between GET and POST request data

  • In a Get request, parameters are displayed in the URL, and in a Post request, parameters are displayed in a Send
  • The Get request sends a small amount of data, but the Post request sends a large amount of data
  • A Get request is less secure and will be cached, whereas a Post request is not. For details on the first difference, see the following two figures:

Fourth, concluding remarks

In fact, network requests via XMLHttpRequest or a wrapped framework are a bit old and messy to configure and invoke. Fetch, which has just emerged in recent years, provides a better alternative. It not only provides a simple and logical way to Fetch resources asynchronously across the network, And it can be easily used by other technologies.

To learn how to use Fetch to request data, poke how Fetch requests common data formats

To learn how Ajax requests background data, please poke Ajax requests background data

Refer to the article

Javascript tutorial

Ajax profile

Never learn AJAX again! (a) AJAX overview

HTTP Rookie Tutorial

The difference between AJAX POST and GET requests