AJAX is a technology used to create fast, dynamic web pages. AJAX enables web pages to update asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.
1. The technology included in ajax
Everyone knows that ajax is not a new technology, but a combination of several original technologies. It is composed of the following technologies.
Represented using CSS and XHTML.
Use DOM model for interaction and dynamic display.
Use XMLHttpRequest to communicate asynchronously with the server.
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 de facto standard. Because almost all major browsers currently support it.
2. How to create ajax
The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object, obtain data from the server, and then use javascript to operate the DOM and update the page. The most critical step in this is to obtain the request data from the server. Creating ajax natively can be divided into the following four steps.
1. Create XMLHttpRequest object
All modern browsers (IE7+, Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects.
Syntax for creating XMLHttpRequest objects:
var xhr = new XMLHttpRequest();
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
To cope with all modern browsers, including IE5 and IE6, please Check whether the browser supports the XMLHttpRequest object. If supported, creates an XMLHttpRequest object. If it is not supported, create an ActiveXObject:
var xhr; if(XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
2. Prepare the request
Initialize the XMLHttpRequest object, accepting three parameters:
xhr.open(method,url,async);
The first parameter represents a string of request type, Its value can be GET or POST.
GET request:
xhr.open("GET",demo.php?name=tsrot&age=24,true);
POST request:
xhr.open("POST",demo.php,true);
The second parameter is the URL to be sent as the target of the request.
The third parameter is true or false, indicating whether the request is issued in asynchronous or synchronous mode. (Default is true, false is generally not recommended)
false: Requests issued in synchronous mode will suspend the execution of all javascript code until the server gets a response. If the browser fails when connecting to the network or downloading files, The page will always hang.
true: A request issued in asynchronous mode. While the request object is sending and receiving data, the browser can continue to load the page and execute other javascript codes.
3. Send request
xhr.send();
Generally, use Ajax to submit The parameters are mostly simple strings. You can directly use the GET method to write the parameters to be submitted into the url parameter of the open method. At this time, the parameters of the send method are null or empty.
GET request:
xhr.open("GET",demo.php?name=tsrot&age=24,true); xhr.send(null);
POST request:
If you need to POST data like an HTML form, please use setRequestHeader() to add HTTP headers. Then specify the data you want to send in the send() method:
xhr.open("POST",demo.php,true); xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xhr.send("name="+userName+"&age="+userAge);
4. Processing the response
xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(xhr.responseText); } }
onreadystatechange event:
When the request is sent to the server, we need to perform some based on response tasks. Whenever readyState changes, the onreadystatechange event is triggered.
readyState property:
0: The object has been created, but the open() method has not been called.
1: The open() method has been called, but the request has not been sent yet.
2: The request has been sent, the headers and status have been received, and are available.
3: Received response from server.
4: After receiving the request data, it means the request has been completed.
status attribute:
200: "OK"
404: Page not found
responseText: Get response data in string form
responseXML: Get response data in XML form
The return value is generally a json string, You can use JSON.parse(xhr.responseText) to convert it into a JSON object.
5. Complete example
demo.html
var xhr; if(XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }; xhr.open("GET","./data.json",true); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(JSON.parse(xhr.responseText).name); } }
data.json
{ "name":"tsrot", "age":24 }
3. Ajax application scenarios
Scenario 1. Data verification
Scenario 2. On demand Get data
Scenario 3. Automatically update the page
4. Advantages and disadvantages of ajax
Advantages:
1. The page does not refresh, and the user experience is good.
2. Asynchronous communication, faster response capability.
3. Reduce redundant requests and reduce server burden
4. Based on standardized and widely supported technology, no need to download plug-ins or applets.
Disadvantages:
1. Ajax kills the back button, which destroys the browser's back mechanism.
2. There are certain safety issues.
3. The support for search engines is relatively weak.
4. Destroyed the exception mechanism of the program.
5. It cannot be accessed directly by URL.