First, Dome,ajax three big strides
<! DOCTYPE html>//Alert (window. ActiveXObject); Window.onload=function(){ varBtn=document.queryselector (' Input '); Btn.onclick=function() {Console.log (1) /** * Instantiation of Ajax Objects ***************************/ varXhr=getxhr (); /** Second, data submission ***********************************/ /*************1. Using the Open () +send () method get***************************/ //in Get formXhr.open ("Get", "06ajax.php?act=json&user=kn",true);//Open () Submit dataXhr.send (); //1). Send () cannot be omitted //2). Get data is sent on the URL //3). Post must be added to the request header /*************2. Using the Open () +send () method post***************************/ //in post form //Xhr.open ("Post", "Http://test.com/06Ajax.php?act=json", true); Cannot access across domains /*Xhr.open ("Post", "06ajax.php?act=json", true); Open () Submit URL xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xhr.send ("user=kn&paw=123");*/ /** Third, data receive ***********onreadystatechang () ***************************/ //essentially 2 kinds of data XML and string //1. StringXhr.onreadystatechange =function(){ //ensure server-side response data is sent if(Xhr.readystate = = 4){ //to ensure that this request must be successful. if(Xhr.status = = 200){ //receiving server-side data varJSON = Xhr.responsetext;//get a string in data JSON formatConsole.log (JSON);//' {' act ': ' JSON ', ' user ': ' kn '} ' /** Use the eval () function to convert * * use "()" to wrap it, the eval () function to force it to be converted to JSON format (JavaScript code) * * Do not use "()" to wrap it, the eval () function recognizes it as an empty block of code*/ vardata = eval ("(" +json+ ")");//Console.log (data);//{"act": "JSON", "User": "KN"}}}} Console.log (XHR); } } //define a function to create a XMLHttpRequest object functiongetxhr () {//declaring XMLHttpRequest Objects varXHR; //created based on different browsers if(window. XMLHttpRequest) {//Other BrowsersXHR =NewXMLHttpRequest (); }Else{ //IE browser (8 and before)XHR =NewActiveXObject ("Microsoft.XMLHTTP"); } //returns the XMLHttpRequest object returnXHR; } </script>Two: the meaning of Ajax
1. What is Ajax?
Ajax is all called "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML),
is not a new programming language, but a technique for creating better, faster, and more interactive Web applications.
It uses:
Use XHTML+CSS to standardize presentation;
Using XML and XSLT for data exchange and related operations;
Asynchronous data communication with the Web server using the XMLHttpRequest object;
Use JavaScript to manipulate document Object model for dynamic display and interaction;
Use JavaScript to bind and manipulate all data.
2. Comparison with traditional Web applications
AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page. Traditional Web pages (without AJAX) if you need to update the content, you must reload the entire page page. How the 3.AJAX works
Ajax works by adding a middle-tier (Ajax engine) between the user and the server, making the user operation asynchronous with the server response. Not all user requests are submitted to the server, such as data validation and processing, to be done by the Ajax engine itself, only to determine the need to read new data from the server and then by the Ajax engine to submit the request to the server.
Ajax has the core of JavaScript, XMLHttpRequest, Dom objects, through the XMLHttpRequest object to send an asynchronous request to the server, from the server to obtain data, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server. The exact code is as shown.XMLHttpRequest Object Method Description
| Method |
Description |
| Abort () |
Stop the current request |
| getAllResponseHeaders () |
Returns all response headers for an HTTP request as a key/value pair |
| getResponseHeader ("header") |
Returns the string value of the specified header |
| Open ("Method", "URL", [asyncflag],["UserName"],["password"]) |
Establish a call to the server. The method parameter can be a GET, post, or put. The URL parameter can be a relative URL or an absolute URL. This method also includes 3 optional parameters, whether asynchronous, user name, password |
| Send (content) |
Send a request to the server |
| setRequestHeader ("header", "value") |
Sets the specified header to the value provided. The open () must be called before any headers can be set. Set the header and send it with the request (' post ' method must be) |
XMLHttpRequest Object Property Description
| |
description description |
| onreadystatechange |
event triggers with state changes that trigger this event handler when each state changes, typically invoking a JavaScript function |
| readyState |
request status. There are 5 desirable values: 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, 4 = completion of |
| responsetext |
Server response, returns the text of the data. |
| responsexml |
The response of the server, which returns a compatible DOM XML Document object for the data, which can be parsed as a DOM object. |
| responsebody |
The topic returned by the server (non-text format) |
| responsestream |
data flow returned by the server |
HTTP status code for the
| status |
server (for example: 404 = "file found at the end", 200 = "Success" &NBSP;, etc.) |
| statustext |
The status text information returned by the server, the corresponding text of the HTTP status code (OK or not Found (not found), and so on) |
Advantages and disadvantages of 4.AJAX
(1). The advantages of Ajax
<1>: No refresh update data.
The biggest advantage of Ajax is the ability to communicate with the server to maintain data without refreshing the entire page. This enables the Web application to respond more quickly to user interactions and avoids sending information that is not changed on the network, reducing user latency and bringing a very good user experience.
<2>. Asynchronously communicates with the server.
Ajax uses asynchronous methods to communicate with the server, without interrupting the user's operations and having more rapid responsiveness. Optimize communication between browser and server, reduce unnecessary data transfer, time and reduce traffic on network.
<3>: Front-end and back-end load balancing.
Ajax can pass on some of the previous server workloads to the client, take advantage of the client's idle ability to handle, reduce server and bandwidth burden, save space and broadband rental costs. and reduce the burden of the server, the principle of Ajax is "on-demand data", can minimize the redundancy request and response to the burden on the server, improve site performance.
<4> standards-based is widely supported.
Ajax is based on standardized and widely supported technologies that do not require a browser plugin or applet to be downloaded, but require the client to allow JavaScript to be executed on the browser. With the maturation of Ajax, a number of libraries that simplify the use of Ajax have been introduced. Similarly, there is another assistive programming technique that provides alternative functionality for users who do not support JavaScript.
<5>: interface and application separation.
Ajax separates the interface in the Web from the application (or the separation of data and rendering), facilitates division of labor, reduces web application errors caused by non-technical changes to the page, improves efficiency, and is more applicable to today's publishing systems.
(2). Disadvantages of Ajax
<1>. Ajax kills back and the history function, which is the destruction of the browser mechanism.
In the case of dynamically updating the page, the user cannot go back to the previous page state because the browser can only remember the static pages in the history. The difference between a fully read page and a page that has been dynamically modified is very subtle; The user will typically want to click the Back button to cancel their previous operation, but in an AJAX application this will not be possible.
The Back button is an important feature of a standard web site, but it does not work well with JS. This is a serious problem with Ajax, because users often want to be able to undo the previous operation by going backwards. So is there any way to do this question? The answer is yes, using Gmail know, Gmail under the Ajax technology to solve the problem, in Gmail can be back, but it does not change the mechanism of Ajax, it is only a relatively stupid but effective way, that is, the user click the Back button to access the history To reproduce the changes on the page by creating or using a hidden iframe. (for example, when a user clicks back in Google Maps, it searches in a hidden iframe and then reflects the search results on an AJAX element to restore the application state to its current state.) )
However, while this problem can be solved, the cost of development is very high and deviates from the rapid development required by the AJAX framework. This is a very serious problem caused by Ajax.
A related view is that using dynamic page updates makes it difficult for users to save a particular state to a collection. The solution for this problem has also occurred, with most of the URL fragment identifiers (often referred to as anchors, which are the parts of the # URL) to keep track of, allowing the user to return to the specified application state. (many browsers allow JavaScript to dynamically update the anchor point, which allows an AJAX application to update the anchor point while updating the display.) These solutions also address many of the arguments that do not support back buttons.
<2>. Security issues with Ajax.
Ajax technology provides users with a good user experience, but also brings new security threats to it enterprises, Ajax technology is like the enterprise data set up a direct channel. This allows developers to inadvertently expose more data and server logic than ever before. The logic of Ajax can be hidden from the client's security scanning technology, allowing hackers to create new attacks from remote servers. And Ajax also makes it difficult to avoid some known security weaknesses, such as cross-site footstep attacks, SQL injection attacks, and credentials-based security vulnerabilities.
<3> Support for search engines is weak.
Support for search engines is weaker. If used improperly, Ajax can increase the flow of network data, thereby reducing the overall system performance.
Ajax principles----Beginner's Chapter