Ajax: Asynchronous JavaScript and XML. Write a simple example:
< Body >
< Form ID = "Form1" Runat = "Server">
< Div >
< ASP : Label ID = "Labeltime" Runat = "Server"> </ ASP : Label >
</ Div >
</ Form >
< Script Type = "Text/JavaScript">
If (! Window. XMLHttpRequest ){
Window. XMLHttpRequest = Function (){
Return new Activexobject ( "Microsoft. XMLHTTP" );
};
}
Function Updateclock (){
VaR Request = New XMLHttpRequest ();
Request. Open ( "Post" , "Timetest. aspx" , False );
Request. Send ( "" );
Document. getelementbyid ("Labeltime" ). Innertext = request. responsetext;
}
Setinterval (updateclock, 1000 );
</ Script >
</ Body >
The current time is written on another page to form a clock.
CodeIt is easy to manipulate an XMLHTTPRequest object to get the server time and then update the time. When the above Code interacts with the server, the page is not refreshed as a whole, but partial refreshing.
However, the above Code is in the request. when open is enabled, the last parameter is false, indicating that the XMLHttpRequest is synchronized. Because Javascript is single-threaded, the thread will be blocked while waiting for the request, if the request takes too long, the browser stops responding.
Although Javascript is single-threaded, XMLHttpRequest can process requests asynchronously. The Code is as follows:
< Body >
< Form ID = "Form1" Runat = "Server">
< Div >
< ASP : Label ID = "Labeltime" Runat = "Server"> </ ASP : Label >
</ Div >
</ Form >
< Script Type = "Text/JavaScript">
If (! Window. XMLHttpRequest ){
Window. XMLHttpRequest = Function (){
Return new Activexobject ( "Microsoft. XMLHTTP" );
};
}
Function Asynrequest (){
VaR Request = New XMLHttpRequest ();
Request. Open ( "Post" , "Timetest. aspx" , True );
Request. onreadystatechange = Function (){
If (Request. readystate = 4 ){
Updateclock (request. responsetext );
}
};
Request. Send ( "" );
}
Function Updateclock (time ){
Document. getelementbyid ( "Labeltime" ). Innertext = time;
}
Setinterval (asynrequest, 1000 );
</ Script >
</ Body >
Ah, it's really hard to have a day without smart reminders.