The key object used by Ajax is the XmlHttpRequest object, but it involves cross-browser issues. Therefore, you need to create a compatible object such:
The Code is as follows:
Function xmlHttpR (){
Var xmlhttp;
If (window. XMLHttpRequest ){
Xmlhttp = new XMLHttpRequest ();
}
Else {
Try {xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP ")}
Catch (e ){
Try {xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Catch (e) {return null;
}
}
Return xmlhttp;
In this way, you can create a cross-browser object;
The following is a simple application of ajax, which is completed using the XmlHttpRequest object;
The Code is as follows:
Var ajaxEl = new Object ();
// AjaxEl is a custom namespace;
AjaxEl. contentLoad = function (url ){
// Cache is enabled in IE browser. Here, the date field is added to the url to prevent IE from using the cache. Of course, Math. random () can also be used to produce a similar effect as getTime;
Url + = "? Date = "+ new Date (). getTime ();
This. req = null;
This. url = url;
// This callback function is the UPDATE function of the data on the page;
This. onload = function (){
// DomEl is the dom element whose ID is # test;
Var domEl = document. getElementById ("test ");
// In addition to the responseText attribute, you can also use responseXml to obtain a data table;
DomEl. innerHTML = this. req. responseText;
}
This. Xmlhttp (url );
}
AjaxEl. contentLoad. prototype = {
Xmlhttp: function (url ){
If (window. XMLHttpRequest ){
This. req = new XMLHttpRequest ();
}
Else {
Try {this. req = new ActiveXObject ("Msxml2.XMLHTTP ")}
Catch (e ){
Try {this. req = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Catch (e) {return null;
}
}
}
If (this. req ){
Var xmlR = this;
This. req. onreadystatechange = function (){
If (xmlR. req. readyState = 4 ){
XmlR. onload. call (xmlR );
}
}
This. req. open ("GET", url, true );
This. req. send (null );
}
}
}
Var xmlE = new ajaxEl. contentLoad ("main. php ");
In main. php, the simple sample code I set here is displayed on the page similar to: now! Time is: 05: 18: 10 am 2011, so that the time can be dynamically changed.
The Code is as follows:
Echo "now! Time is: ". date (" H: I: s a Y ");