For simplicity and clarity, I will only test it in HTML; I will not talk nonsense if I write it clearly in annotations;
Many companies may prevent you from using any Ajax framework to implement the Ajax effect during the interview. Although this code looks painful, there is no other way, you can also remember it if you don't remember it (in fact, it's not that difficult to remember it ......)
Readystate indicates the processing status of the XMLHTTPRequest object: 0: the XMLHTTPRequest object has not been initialized yet. 1: the XMLHTTPRequest object starts sending requests. 2: The request of the XMLHTTPRequest object is sent completely. 3: the XMLHTTPRequest object starts to read the server's response. 4: the XMLHTTPRequest object reads the server and the response ends.
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Ajax effect without using the Ajax framework </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Function btnclick (){
VaR XMLHTTP = new activexobject ("Microsoft. XMLHTTP"); // create an XMLHTTP object, which is equivalent to WebClient
If (! XMLHTTP ){
Alert ("An error occurred while creating the XMLHTTP object! ");
Return false;
}
XMLHTTP. Open ("Post", "getdate. ashx", false); // you are going to send a POST request to the getdate. ashx (General handler) of the server.
// XMLHTTP is not a synchronous request by default (also recommended), that is, the open method does not return the data returned by the server as the downloadstring of WebClient. It is asynchronous, therefore, the onreadystatechange event must be monitored anonymously;
XMLHTTP. onreadystatechange = function (){
If (XMLHTTP. readystate = 4) {// If the XMLHTTPRequest object reads the server, the response ends;
If (XMLHTTP. Status = 200) {// If the status code is 200, the processing is successful;
Document. getelementbyid ("getdate"). value = XMLHTTP. responsetext; // The responsetext attribute is the text returned by the server.
} Else {
Alert ("ajax server return error ");
}
}
}
XMLHTTP. Send (); // The request starts to be sent.
}
</SCRIPT>
</Head>
<Body>
<Input id = "getdate" type = "text"/>
<Input type = "button" value = "request time" onclick = "btnclick ()"/>
</Body>
</Html>
Getdate. ashx (General handler) code:
Using system;
Using system. Web;
Namespace Ajax
{
/// <Summary>
/// Getdate: Get the server time
/// </Summary>
Public class getdate: ihttphandler
{
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/plain ";
Context. response. Write (datetime. Now. tostring ());
}
Public bool isreusable
{
Get
{
Return false;
}
}
}
}