<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> XMLHttpRequest Ajax demo </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
VaR req; // defines a variable to create an XMLHTTPRequest object.
Function creatreq () // create XMLHttpRequest, start with Ajax
{
VaR url = "ajaxserver. aspx"; // The server address to be requested
If (window. XMLHttpRequest) // non-IE browser and IE7 (version 7.0 and later), create with XMLHTTPRequest object
{
Req = new XMLHttpRequest ();
}
Else if (window. activexobject) // IE (version 6.0 and earlier) browser creates an activexobject object. If ActiveX is disabled in your browser, it may fail .{
Req = new activexobject ("Microsoft. XMLHTTP ");
}
If (req) // create XMLHttpRequest
{
Req. Open ("get", URL, true); // establish a connection with the server (Request Method post or get, address, true indicates asynchronous)
Req. onreadystatechange = callback; // specify the callback function.
Req. Send (null); // send the request
}
}
Function callback () // callback function, which processes responses to the server and monitors the response status.
{
If (req. readystate = 4) // if the request status is 4, the request is successful.
{
If (req. Status = 200) // HTTP status 200 indicates OK
{
Dispaly (); // All statuses are successful. Execute this function to display data
}
Else // HTTP return status failed
{
Alert ("server return status" + Req. statustext );
}
}
Else // The Request status is not successful yet, and the page waits
{
Document. getelementbyid ("mytime"). innerhtml = "loading data ";
}
}
Function dispaly () // receives and displays the data returned by the server.
{
Document. getelementbyid ("mytime"). innerhtml = Req. responsetext;
}
</SCRIPT>
</Head>
<Body>
<Div id = "mytime"> </div>
<Input id = "button1" type = "button" value = "get time" onclick = "creatreq ();"/>
</Body>
</Html>
Pay attention to the execution sequence of Ajax.
Onchange () onpropertychange () is more sensitive to actions whose input type is text than the former. It is possible that onchange () will not change with the changes in the former, however, onpropertychange () will definitely change with the value.
When the returned value is written in the final condition, pay attention to the position of the function.
The methods used for XML operations are the same as those used for XML operations, such as getelementsbytagname (), and. firstchild. Data, nodevalue.
The order of Ajax execution is open, onreadystatechange, and send is transmitted in the form of stream.
The servlet must be transmitted and valid in the form of a stream. Resp. setcontenttype (), which must be set accordingly.