1. What is ajax?
AJAX = Asynchronous JavaScript and XML (Asynchronous JavaScript and XML).
AJAX is not a new programming language, but a new method to use existing standards.
AJAX is to exchange data with the server and updates the arts section of the page, without reloading the entire page. AJAX is a technique for creating fast dynamic web pages.
By exchanging small amounts of data with the server behind the scenes, AJAX can make asynchronous page updates. This means that, for certain parts of the page to be updated without reloading the entire page.
Traditional web page (do not use AJAX) If you need to update the entire page surface content, essential overloaded.
2. How to use?
1, create XMLHttpRequest object
var xmlHttp = new XMLHttpRequest()
(Compatibility issues)
In order to cope with all modern browsers, including IE5 and IE6, please check whether the browser supports the XMLHttpRequest object. If supported, XMLHttpRequest objects are created. If not, create ActiveXObject:
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"); }
2, the server sends a request to
We use the XMLHttpRequest object's open () and send () method:
xmlhttp.open (
Method : request type; the GET or the POST,
URL : location of the file on the server,
the async : to true (asynchronous) or false (synchronous)
); Xmlhttp.send (); // send a post request only
if the request is a post, header information needs to be sent
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
3 , response
ResponseText responseXML property or use the XMLHttpRequest object to obtain the content of the response.
Attributes | description |
---|---|
responseText | Response data string obtained. |
responseXML | XML is obtained in the form of the response data. |
4, the onreadystatechange event
Attributes | description |
---|---|
onreadystatechange | Storage function (or function name), whenever the readyState property changes, it will call the function. |
readyState | There XMLHttpRequest state. Vary from 0-4.
|
status | 200: "OK" 404: Page Not Found |
When readyState state equal to 4 and 200, a response indicating ready:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }