I. Overview
1. Program Execution Flow:
(1) Click id= "TESTBTN" button, trigger validate ();
(2) Validate () calls the Request.open method to interact with the server (in the JSP page specified by the URL, the writer writes an XML file and returns it to request with Responsexml);
(3) When the interaction state changes, the callback function is called, the callback determines the state, and if the interaction succeeds, the value in the Responsexml is read;
(4) dynamically generated innerHTML is returned to the page based on the value read in the Responsexml.
Second, the Code
1.index.html
1 <HTML>2 <Head>3 <Script>4 5 functionValidate () {6 varIDfield=document.getElementById ("testbtn");7 varURL= "validate.jsp?id="+Escape (IDfield);8 req= NewXMLHttpRequest ();9 Req.open ("GET", URLs,true);Ten Req.onreadystatechange=callback; One Req.send (NULL); A - } - the functioncallback () { - if(Req.readystate== 4){ - //alert (req.status); - //alert (req.responsexml); + //alert (msg); - if(Req.status== $){ + varmsg=Req.responseXML.getElementsByTagName ("msg")[0]; A setmsg (msg.childnodes[0].nodevalue); at } - } - } - - functionsetmsg (msg) { - varMDiv=document.getElementById ("ajaxmsg"); in if(msg== "ABC"){ - mdiv.innerhtml= "<div>america Born chinese</div>"; to }Else if(msg== "123"){ + mdiv.innerhtml= "<div> Arabic numerals </div>"; - } the * } $ </Script>Panax Notoginseng </Head> - <Body> the <inputtype= "Submit"ID= "Testbtn"onclick= "Validate ()"value= "MyButton"/> + <spanID= "Ajaxmsg"></span> A </Body> the </HTML>
2.validate.jsp
1 <%2 response.setcontenttype ("Text/xml"); 3 response.setheader ("Cache Control", "no Store"); 4 response.setheader ("Pragam", "No-cache"); 5 response.setdateheader ("Expires", 0); 6 Response.getwriter (). Write ("<msg>abc</msg>"); 7 %>
Iii. Results of operation
Simple Ajax Example