First of all, what is AJAX?
AJAX = asynchronous JavaScript and XML.
AJAX is a technology for creating fast dynamic web pages.
AJAX enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that a part of the page can be updated without reloading the entire page.
Traditional web pages (without AJAX) need to reload the entire web page if they need to update the content.
There are many application cases using AJAX: Sina Weibo, Google maps, Kaixin, etc.
1. AJAX - create XMLHttpRequest object
XMLHttpRequest object
All modern browsers support XMLHttpRequest objects (IE5 and IE6 use AcActiveXObject).
XMLHttpRequest is used to exchange data with the server in the background. This means that a part of the page can be updated without reloading the entire page.
All modern browsers (IE7 +, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.
Syntax for creating XMLHttpRequest object:
variable = new XMLHttpRequest();
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
variable=new ActiveXObject( "Microsoft.XMLHTTP" );
In response to all modern browsers, including IE5 and IE6, check that the browser supports XMLHttpRequest objects. If supported, create the XMLHttpRequest object. If not, create an ActiveXObject:
1.1 XHR creation object:
var xmlhttp; if ( window.XMLHttpRequest ) {// code for IE7+, Firefox, Chrom, Safari, Opera xmlhttp = new XMLHttpRequest(); } else {// code for IE5, IE6 xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" ); }
1.2 AJAX - send request to server
The XMLHttpRequest object is used to exchange data with the server.
Send request to server
To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object:
xmlhttp.open("GET","test1.txt",true); //Specifies the type of request, the URL, and whether to process the request asynchronously. xmlhttp.send(); //Send the request to the server.
Method | describe |
---|---|
open(method,url,async) |
Specifies the type of request, the URL, and whether to process the request asynchronously.
|
send(string) |
Send the request to the server.
|
GET or POST?
GET is simpler and faster than POST, and works in most cases.
However, use POST requests when:
- Cannot use cache file (update file or database on server)
- Send a large amount of data to the server (POST has no data limit)
- When sending user input with unknown characters, POST is more stable and reliable than GET
GET request
A simple GET request:
xmlhttp.open("GET","demo_get.asp",true); xmlhttp.send();
POST request
A simple POST request:
xmlhttp.open("POST","demo_post.asp",true); xmlhttp.send();
If you need POST data like an HTML form, use setRequestHeader() to add the HTTP header. Then specify the data you want to send in the send() method:
xmlhttp.open("POST","ajax_test.asp",true); Xmlhttp. Setrequestheader ("content type", "application / x-www-form-urlencoded"); / / add TTTP header to the request; xmlhttp.send("fname=Bill&lname=Gates");
Method | describe |
---|---|
setRequestHeader(header,value) |
Add an HTTP header to the request.
|
url - file on server
The url parameter of the open() method is the address of the file on the server:
xmlhttp.open("GET","ajax_test.asp",true);
The file can be any type of file, such as. txt and. xml, or server script files, such as. asp and. php (capable of executing tasks on the server before returning a response).
Asynchronous - True or False?
AJAX refers to Asynchronous JavaScript and XML.
If the XMLHttpRequest object is to be used for AJAX, the async parameter of its open() method must be set to true:
xmlhttp.open("GET","ajax_test.asp",true);
Sending asynchronous requests is a huge step forward for web developers. Many tasks performed on the server are quite time-consuming. Before AJAX, this may cause the application to hang or stop.
With AJAX, JavaScript doesn't have to wait for a response from the server, but instead:
- Execute additional scripts while waiting for server response
- Process the response when it is ready
Async = true
When async=true is used, specify the function to execute when the response is in a ready state in the onreadystatechange event:
xmlhttp.onreadystatechange=function() { If (xmlhttp. ReadyState = = 4 & & xmlhttp. Status = = 200) / / request completed and returned successfully { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","test1.txt",true); xmlhttp.send();
Async = false
To use async=false, change the third parameter in the open() method to false:
xmlhttp.open("GET","test1.txt",false);
We don't recommend async=false, but for some small requests, it's OK.
Remember that JavaScript will wait until the server response is ready to continue. If the server is busy or slow, the application hangs or stops.
Note: when you use async=false, do not write the onreadystatechange function - just put the code after the send() statement:
xmlhttp.open("GET","test1.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
1.3 AJAX - server response
To get a response from the server, use the responseText or responseXML attribute of the XMLHttpRequest object.
attribute | describe |
---|---|
responseText | Gets the response data as a string. |
responseXML | Get the response data in XML. |
responseText property
If the response from the server is not XML, use the responseText property.
The responseText property returns a response as a string, so you can use this:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Example:
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/ajax/test1.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">adopt AJAX Changing content</button> </body> </html>
responseXML attribute
If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute:
Request books.xml File and parse the response:
xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt;
Example:
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; var txt,x,i; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("title"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","/example/xmle/books.xml",true); xmlhttp.send(); } </script> </head> <body> <h2>My Book Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my book collection list</button> </body> </html>
1.4 AJAX - onreadystatechange event
When the request is sent to the server, we need to perform some response based tasks.
Whenever the readyState changes, the onreadystatechange event is triggered.
The readyState property holds the state information for XMLHttpRequest.
Here are three important properties of the XMLHttpRequest object:
attribute | describe |
---|---|
onreadystatechange | Stores a function (or function name) that is called whenever the readyState property changes. |
readyState |
The state in which XMLHttpRequest is stored. Changes from 0 to 4.
|
status |
200: "OK" 404: page not found |
In the onreadystatechange event, we specify the tasks to be performed when the server response is ready to be processed.
When readyState equals 4 and state is 200, the response is ready:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
Example:
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/ajax/test1.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">adopt AJAX Changing content</button> </body> </html>
Note: the onreadystatechange event is triggered five times (0 - 4), corresponding to each change of readyState.
Using the Callback function
A callback function is a function that is passed as a parameter to another function.
If there are multiple AJAX tasks on your site, you should write a standard function for creating XMLHttpRequest objects and call that function for each AJAX task.
The function call should contain the URL and the tasks to perform when the onreadystatechange event occurs (each call may be different):
function myFunction() { loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); }
Example:
<html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc(url,cfunc) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction() { loadXMLDoc("/ajax/test1.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">adopt AJAX Changing content</button> </body> </html>
// code for IE7+, Firefox, Chrome, Opera, Safari