Ajax principle is enough
Foreword
AJAX stands for "Asynchronous Javascript And XML", which refers to a web development technology for creating interactive web applications. AJAX is a technique for creating fast and dynamic web pages. It allows developers to only obtain data from the server (instead of pictures, HTML documents and other resources), and the transmission of Internet resources has become unprecedentedly lightweight and pure, which stimulates the creativity of developers and makes various Powerful web sites and Internet applications have sprung up like mushrooms after a rain, constantly surprising people.
1. What is Ajax
Ajax is a web development technology that requests data asynchronously, which is helpful for improving user experience and page performance. Simply put, Ajax loads background data through asynchronous requests and renders it on the web page without needing to refresh the page. Common application scenarios include form verification whether the login is successful, Baidu search drop-down box prompts, and express tracking number query. The purpose of Ajax is to improve the user experience and reduce the amount of network data transmission . At the same time, since the AJAX request fetches data instead of HTML documents, it also saves network bandwidth and makes the Internet surfing experience smoother for Internet users.
2. what is the principle of Ajax
Before explaining the principle of Ajax, we might as well give an example of "the leader wants to ask Xiao Li to report on his work". If the leader wants to ask Xiao Li about something, he entrusts the secretary to call Xiao Li, and then he does other things himself until the secretary tells him He Xiaoli has arrived, and finally Xiaoli reports to the leader.
The Ajax request data process is similar to "The leader wants to find Xiao Li to report the work". The core dependency is the XMLHttpRequest object provided by the browser, which acts as a secretary, enabling the browser to issue HTTP requests and receive HTTP responses. The browser then does other things, and then renders the page after receiving the data returned by XHR.
After understanding how Ajax works, let's discuss how to use Ajax.
3. 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);//The string parameter is used only when the post request is made, otherwise no parameter is required.
- method: Type of request; GET or POST
- url: the location of the file on the server
- async: true (asynchronous) or false (synchronous)
Note: The post request 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"); //The post request parameters are placed in send, that is, the request body
3. Server response processing (distinguish between synchronous and asynchronous)
- responseText gets the response data in string form.
- responseXML Gets the response data in XML.
① Synchronous processing
1. xhr.open("GET","info.txt",false);
2. xhr.send();
3. document.getElementById("myDiv").innerHTML=xhr.responseText; //Get the data and display it directly on the page
② Asynchronous processing
It is relatively complex and needs to be handled in the request state change event.
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, which is used to identify the current state of the XMLHttpRequest object.
- readyState has a total of 5 state values, 0~4 respectively, each value represents 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: Receive -- part of the response data has been received;
- 4: Completed -- all response data has been received and can be used on the client side;
What is status?
The HTTP status code (status) consists of three decimal numbers. The first decimal number defines the type of the status code, and the last two numbers have no classification function. There are 5 types of HTTP status codes:
Common Status Codes
There are 40 HTTP status codes recorded in RFC2616 alone, and if the extensions such as WebDAV (RFC4918, 5842) and additional HTTP status codes (RFC6585) are added, the number reaches more than 60 kinds. Next, we will introduce some of these representative status codes.
- 200 means that the request from the client was processed normally on the server side.
- 204 indicates that the request was processed successfully, but no resources were returned.
- 301 means a permanent redirect. This status code indicates that the requested resource has been assigned a new URI, and the URI to which the resource now refers should be used in the future.
- 302 means a temporary redirect.
- 304 indicates that the client sends a conditional request (referring to the request message using the GET method that contains any header of if-matched, if-modified-since, if-none-match, if-range, if-unmodified-since) The server allows the request to access the resource, but returns 304Modified directly after the request does not meet the conditions (the server-side resource has not changed, and the client's unexpired cache can be used directly)
- 400 means there is a syntax error in the request message. When an error occurs, you need to modify the content of the request and send the request again.
- 401 means Unauthorized, the current request requires user authentication
- 403 indicates that access to the requested resource was denied by the server
- 404 means the requested resource could not be found on the server. In addition, it can also be used when the server side rejects the request and does not want to give a reason.
- 500 means an error occurred on the server side while executing the request. It may also be a bug in the web application or some temporary failure.
- 503 indicates that the server is temporarily overloaded or is undergoing maintenance downtime and cannot process requests now.
③ The difference between GET and POST request data
- When using the Get request, the parameters are displayed in the URL, and when using the Post method, they are placed in the send
- Use the Get request to send a small amount of data, and the Post request to send a large amount of data
- Using Get requests has low security and will be cached, while Post requests are on the contrary
. For the first difference, see the following two figures for details:
4. Conclusion
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. It not only provides a kind of Simple, logical way to fetch resources asynchronously across the network, and can be easily used by other technologies.