Home > Article > Web Front-end > Detailed explanation of how AJAX works and its advantages and disadvantages
This article will explain the working principle of ajax and its related content.
1.AJAX stands for "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), which is a web development technology for creating interactive web applications. It uses:
Use XHTML CSS to standardize rendering;
Use XML and XSLT for data exchange and related operations;
Use XMLHttpRequest The object communicates asynchronously with the Web server;
Use JavaScript to operate the Document Object Model for dynamic display and interaction;
Use JavaScript to bind and process all data.
2. Traditional Web application interaction involves the user triggering an HTTP request to the server. The server processes it and then returns a new HTHL page to the client. Whenever the server processes a request submitted by the client, The client can only wait idle, and even if it is just a small interaction and only needs to get a simple piece of data from the server, a complete HTML page must be returned, and the user has to waste time and bandwidth to re-read it every time. Take the entire page. This approach wastes a lot of bandwidth. Since each application interaction requires sending a request to the server, the application's response time depends on the server's response time. This results in a user interface that is much less responsive than native apps.
Different from this, an AJAX application can only send and retrieve the necessary data to the server. It uses SOAP or some other XML-based Web Service interface, and uses JavaScript on the client to process the data from the server. response. Because less data is exchanged between the server and the browser, we see more responsive applications as a result. At the same time, a lot of processing work can be completed on the client machine that makes the request, so the processing time of the Web server is also reduced.
3. The working principle of AJAX: The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server, so that the user operation and the server response are asynchronous. Not all user requests are submitted to the server. Some data verification and data processing are left to the Ajax engine itself. Only when it is determined that new data needs to be read from the server, the Ajax engine will submit the request to the server on its behalf.
The core of Ajax is composed of JavaScript, XMLHTTPRequest, and DOM objects. It sends asynchronous requests to the server through the XmlHttpRequest object, obtains data from the server, and then uses JavaScript to operate the DOM and update the page. The most critical step in this is to obtain the request data from the server. Let's learn about these objects.
(1).XMLHTTPRequest object
One of the biggest features of Ajax is that it can transmit or read and write data to the server without refreshing the page (also known as updating the page without refreshing). This feature is mainly Thanks to the XMLHTTP component XMLHTTPRequest object.
XMLHttpRequest object method description:
abort(): Stop the current request
getAllResponseHeaders(): Return all response headers of the HTTP request as key/value pairs
getResponseHeader("header"): Returns the string value of the specified header
open("method","URL",[asyncFlag],["userName"],["password"] ): Makes a call to the server. The method parameter can be GET, POST or PUT. The url parameter can be a relative URL or an absolute URL. This method also includes 3 optional parameters, whether it is asynchronous, username, password
send(content): Send a request to the server
setRequestHeader("header", "value"): Sets the specified header to the supplied value. open() must be called before setting any headers. Set header and send it together with the request ('post' method is required)
XMLHttpRequest Object attribute description:
onreadystatechange: event trigger for state change, every time the state changes Triggering this event handler usually calls a JavaScript function
readyState: the requested state. There are 5 possible values: 0 = Uninitialized, the object has been created, but it has not been initialized (the open method has not been called), 1 = Loading, the object has been created, and the send method has not been called, 2 = Loaded, the send method has been called, However, the current status and http headers are unknown. 3 = During the interaction, some data has been received. Because the response and http headers are incomplete, errors will occur when obtaining some data through responseBody and responseText. 4 = Completed, the data reception is completed, and you can Get the complete response data through responseXml and responseText
responseText: The server's response, the text of the returned data.
responseXML: The server's response returns a DOM-compatible XML document object of data. This object can be parsed into a DOM object.
responseBody: The subject returned by the server (non-text format)
responseStream: The data stream returned by the server
status: The HTTP status code of the server (such as: 404 = "File not found", 200 "Success", etc.)
statusText: Status text information returned by the server, corresponding text of the HTTP status code (OK or Not Found (not found), etc.)
The Ajax engine is actually a relatively complex JavaScript application used to process user requests, read and write servers, and change DOM content. JavaScript's Ajax engine reads the information and interactively rewrites the DOM. This allows web pages to be seamlessly reconstructed, that is, changing page content after the page has been downloaded. This is what we have been using extensively with JavaScript and the DOM. method, but to make a web page truly dynamic, it requires not only internal interaction, but also data acquisition from the outside. In the past, we let users enter data and change the content of the web page through the DOM, but now, XMLHTTPRequest allows us to Read and write data on the server without reloading the page, minimizing user input.
Ajax separates the interface and application in the WEB (it can also be said to separate data and presentation). In the past, there was no clear boundary between the two. The separation of data and presentation is conducive to Division of labor reduces WEB application errors caused by non-technical personnel modifying pages, improves efficiency, and is more suitable for current publishing systems. You can also transfer some of the previous work burdened by the server to the client, which is beneficial to the client's idle processing power.
4. Advantages of AJAX
f35d6e602fd7d0f0edfa6f7d103c1b57. Update data without refreshing.
The biggest advantage of AJAX is that it can communicate with the server to maintain data without refreshing the entire page. This allows web applications to respond to user interactions more quickly and avoids sending unchanged information over the network, reducing user waiting time and bringing a very good user experience.
2cc198a1d5eb0d3eb508d858c9f5cbdb. Communicate with the server asynchronously.
AJAX uses an asynchronous method to communicate with the server, without interrupting the user's operation, and has a faster response capability. Optimizes the communication between Browser and Server, reducing unnecessary data transmission, time and data traffic on the network.
5bdf4c78156c7953567bb5a0aef2fc53. Front-end and back-end load balancing.
AJAX can transfer some of the work previously burdened by the server to the client, using the client's idle capabilities to process it, reducing the burden on the server and bandwidth, and saving space and broadband rental costs. And to reduce the burden on the server, the principle of AJAX is to "get data on demand", which can minimize the burden on the server caused by redundant requests and responses and improve site performance.
23889872c2e8594e0f446a471a78ec4c. Widely supported based on standards.
AJAX is based on standardized and widely supported technology. It does not require downloading browser plug-ins or small programs, but requires the customer to allow JavaScript to be executed on the browser. As Ajax matures, some program libraries that simplify the use of Ajax have also come out. Likewise, another assistive programming technology has emerged to provide alternative functionality for users who do not support JavaScript.
43ad812d3a971134e40facaca816c822. The interface is separated from the application.
Ajax separates the interface and application in the WEB (which can also be said to separate data and presentation), which is conducive to division of labor and cooperation, reduces WEB application errors caused by non-technical personnel modifying the page, improves efficiency, and also More suitable for current publishing systems.
5.Disadvantages of ajax
f35d6e602fd7d0f0edfa6f7d103c1b57.AJAX kills the Back and History functions, which is a destruction of the browser mechanism.
In the case of dynamically updated pages, users cannot return to the previous page state because the browser can only remember static pages in the history. The difference between a page that has been read completely and a page that has been dynamically modified is very subtle; users will often expect that clicking the back button will cancel their previous operation, but in an Ajax application, this will not be possible. .
The back button is an important function of a standard web site, but it cannot cooperate well with js. This is a serious problem caused by Ajax, because users often hope to cancel the previous operation by going back. So is there any solution to this problem? The answer is yes. Those who have used Gmail know that the Ajax technology used under Gmail solves this problem. You can go back under Gmail. However, it does not change the mechanism of Ajax. It is just a stupid but effective one. The way to do this is by creating or using a hidden IFRAME to reproduce the changes on the page when the user clicks the back button to access the history. (For example, when the user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search results onto the Ajax element to restore the application state to what it was at that time.)
However, although this problem can be solved, the development cost it brings is very high and is contrary to the rapid development required by the Ajax framework. This is a very serious problem caused by Ajax.
A related point is that using dynamic page updates makes it difficult for users to save a specific state to favorites. Solutions to this problem have also emerged, most of which use URL fragment identifiers (often called anchors, the part after the # in the URL) to keep track and allow the user to return to a specified application state. (Many browsers allow JavaScript to dynamically update anchors, which allows Ajax applications to update the anchor simultaneously with the displayed content.) These solutions also resolve many of the arguments about not supporting the back button.
2cc198a1d5eb0d3eb508d858c9f5cbdb.AJAX security issues.
AJAX technology not only brings a good user experience to users, but also brings new security threats to IT companies. Ajax technology is like establishing a direct channel for enterprise data. This allows developers to inadvertently expose more data and server logic than before. Ajax logic can be hidden from client-side security scanning technologies, allowing hackers to create new attacks from remote servers. Ajax is also difficult to avoid some known security weaknesses, such as cross-site scripting attacks, SQL injection attacks, and Credentials-based security vulnerabilities, etc.
5bdf4c78156c7953567bb5a0aef2fc53. Weak support for search engines.
The support for search engines is relatively weak. If used improperly, AJAX will increase network data traffic, thereby reducing the performance of the entire system.
23889872c2e8594e0f446a471a78ec4c. Destroy the exception handling mechanism of the program.
At least from the current perspective, Ajax frameworks such as Ajax.dll and Ajaxpro.dll will destroy the exception mechanism of the program. Regarding this problem, I have encountered it during the development process, but after checking, there is almost no relevant introduction on the Internet. Later, we did an experiment and used Ajax and traditional form submission modes to delete a piece of data... which brought great difficulties to our debugging.
43ad812d3a971134e40facaca816c822. Violates the original intention of URL and resource positioning.
For example, if I give you a URL address, if Ajax technology is used, maybe what you see under the URL address is different from what I see under this URL address. This is contrary to the original intention of resource positioning.
efbfa0de8737dc86eae413541a49df20.AJAX does not support mobile devices well.
Some handheld devices (such as mobile phones, PDAs, etc.) currently do not support Ajax very well. For example, when we open a website using Ajax technology on the mobile phone's browser, it currently does not support it.
40107655ec554331c1c6222ab67a141c. The client is too fat and too much client code causes development costs.
The writing is complex and error-prone; there are many redundant codes (it is a common problem of AJAX to include js files in layers, plus a lot of server-side code in the past is now placed on the client); it destroys the original features of the Web standard.
6. AJAX points to note and applicable and inapplicable scenarios
(1). Points to note
When developing Ajax, network delay - that is The interval between a user’s request and the server’s response—needs careful consideration. Not giving the user a clear response, not properly pre-reading the data, or improperly handling the XMLHttpRequest will cause the user to experience a delay that they don't want to see and that they cannot understand. A common solution is to use a visual component to tell the user that the system is performing background operations and reading data and content.
(2).Ajax applicable scenarios
f35d6e602fd7d0f0edfa6f7d103c1b57. Form-driven interaction
2cc198a1d5eb0d3eb508d858c9f5cbdb.Deep-level tree navigation
5bdf4c78156c7953567bb5a0aef2fc53. Fast user-to-user communication response
23889872c2e8594e0f446a471a78ec4c. Insignificant scenarios such as voting, yes/no, etc.
43ad812d3a971134e40facaca816c822. Process the data Scenarios for filtering and manipulating related data
efbfa0de8737dc86eae413541a49df20. Ordinary text input prompts and auto-complete scenarios
(3). Scenarios where Ajax is not applicable
acc80a873886d8118be81a328be9ec64.Partially simple form
2cc198a1d5eb0d3eb508d858c9f5cbdb.Search
5bdf4c78156c7953567bb5a0aef2fc53.Basic navigation
23889872c2e8594e0f446a471a78ec4c.Replace large amounts of text
43ad812d3a971134e40facaca816c822.Manipulation of presentation
7.Technology included in ajax
Everyone knows that ajax is not a new technology, but several original technologies combination. It is composed of the following technologies.
1. Use CSS and XHTML to express.
2. Use DOM model for interaction and dynamic display.
3. Use XMLHttpRequest to communicate asynchronously with the server.
4. Use javascript to bind and call.
Among the above technologies, except for the XmlHttpRequest object, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C, it is already a A de facto standard as almost all major browsers currently support it.
Example:
function CreateXmlHttp() { //非IE浏览器创建XmlHttpRequest对象 if(window.XmlHttpRequest) { xmlhttp =newXmlHttpRequest(); } //IE浏览器创建XmlHttpRequest对象 if(window.ActiveXObject) { try{ xmlhttp =newActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try{ xmlhttp =newActiveXObject("msxml2.XMLHTTP"); } catch(ex) { } } } } functionUstbwuyi() { vardata = document.getElementById("username").value; CreateXmlHttp(); if(!xmlhttp) { alert("创建xmlhttp对象异常!"); returnfalse; } xmlhttp.open("POST", url,false); xmlhttp.onreadystatechange =function() { if(xmlhttp.readyState == 4) { document.getElementById("user1").innerHTML = "数据正在加载..."; if(xmlhttp.status == 200) { document.write(xmlhttp.responseText); } } } xmlhttp.send(); }
This article explains the working principle of ajax and its related usage. For more related knowledge, please pay attention to php Chinese website .
Related recommendations:
N ways to obtain elements in JS and their dynamic and static discussions
DOM of JavaScript complete summary Element
implements jquery lazy loading and returns to the top
The above is the detailed content of Detailed explanation of how AJAX works and its advantages and disadvantages. For more information, please follow other related articles on the PHP Chinese website!