As the saying goes, it is easy to say that it is easy to do. It seems easy to compile on programming. Although there is no new technology in ajax, it is just the transformation of ideas and the integration of old technologies, however, there are still a lot of problems when starting to work. First, I often use Firefox, and I immediately encountered the innerText incompatibility problem in Firefox. At first, I couldn't find the cause, later, it suddenly turned out to be a compatibility issue. Baidu, of course, should use the textContent method in ff, and must follow the w3c standard to use getElementById to get the div, you cannot write id directly in diagrams to save trouble. If you do it in IE, you won't know it in Firefox or other browsers. Follow the standard to make it readable.
Code:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Strict // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<Html>
<Head>
<Title> Ajax's first classic example: Hello World </title>
<Script type = "text/javascript">
Var xmlHttp;
Function createXMLHttpRequest (){
If (window. ActiveXObject ){
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XmlHttp = new XMLHttpRequest ();
}
}
Function startRequest (){
CreateXMLHttpRequest ();
Try {
XmlHttp. onreadystatechange = handleStateChange;
XmlHttp. open ("GET", "data. xml", true );
XmlHttp. send (null );
} Catch (exception ){
Alert ("The resource you want to access does not exist! ");
}
}
Function handleStateChange (){
If (xmlHttp. readyState = 4 ){
If (xmlHttp. status = 200 | xmlHttp. status = 0 ){
// Retrieve the xml dom object
Var xmlDOM = xmlHttp. responseXML;
// Get the root of the XML document
Var root = xmlDOM.doc umentElement;
Try
{
// Obtain the <info> result
Var info = root. getElementsByTagName ('info ');
// Obtain the string
Var str_data = info [0]. firstChild. data;
// Change the content of the div and call the changeText function. Note that IE and FF are different.
ChangeText (info [0]. firstChild. data, 'showtext ');
// InnerHTML is the same
Document. getElementById ("showTextHTML"). innerHTML = '<strong>' + info [0]. firstChild. data + '</strong> ';
} Catch (exception)
{
}
}
}
}
Function changeText (str, element) {// compatible with IE and FF
If (navigator. appName. indexOf ("Explorer")>-1 ){
Document. getElementById (element). innerText = str;
} Else {
Document. getElementById (element). textContent = str;
}
}
</Script>
</Head>
<Body>
<Div>
<Input type = "button" value = "return ajax responseXML's value"
Onclick = "startRequest ();"/>
</Div>
<Div id = "showText"> </div>
<Div id = "showTextHTML"> </div>
</Body>
</Html>