1. Creating Ajax Objects
<Scripttype= "Text/javascript"> //Creating an Ajax asynchronous Object functionCreateajax () {varAjax= NULL; Try{ //if Ie5=ie12.Ajax= NewActiveXObject ("Microsoft.XMLHTTP"); }Catch(E1) {Try{ //if it's non-ie,Ajax= NewXMLHttpRequest (); }Catch(E2) {alert ("Async objects are not supported in your browser, please change the browser"); } } returnAjax; } </Script>
2. Add Get Time button
Current time:<id= "Time"></span><BR /><ID= "ButtonID" type= "button" value= "Get current Time"/><p/>
3. Processing the data returned by Ajax in HTML
<Scripttype= "Text/javascript">document.getElementById ("ButtonID"). onclick= function(){ //NO1) Creating an Ajax asynchronous Object varAjax=Createajax (); //NO2) ready to send the request varMethod= "GET"; varURL= "${pagecontext.request.contextpath}/ajaxtimeservlet?time=" + NewDate (). GetTime (); Ajax.open (Method,url); //NO3) actually sends the data of the request body to the server, if there is no data in the request body, it is represented by nullAjax.send (NULL); //-------------------------------------------------------------Wait //NO4) Ajax asynchronous object constantly listens for server response status 0-1-2-3-"4" //You must change the state to trigger function () {} //if the state is always 4-4-4-4-4, it will not trigger the function () {}Ajax.onreadystatechange= function(){ //If the status code is 4, if(Ajax.readystate== 4){ //If the response code is 200, if(Ajax.status== $){ //NO5) Gets the HTML data for the server response from the Ajax asynchronous object varNowstr=Ajax.responsetext; //NO6) Dynamically add results to the label specified in the Web page according to DOM rules varspanelement=document.getElementById (" Time"); Spanelement.innerhtml=Nowstr; } } } }
4. Java's handling of Ajax
/*** No need to refresh the entire Web page to display the current time of the server response*/ Public classAjaxtimeservletextendsHttpServlet { Public voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {simpledateformat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Nowstr= Sdf.format (NewDate ()); //stream the results to an Ajax asynchronous objectResponse.setcontenttype ("Text/html;charset=utf-8"); PrintWriter PW=Response.getwriter (); Pw.write (NOWSTR); Pw.flush (); Pw.close (); }}
Ajax Asynchronous server Get time