一、概述
1.程序执行流程:
(1)点击id="testBtn"的按钮,触发validate();
(2)validate()中有调用request.open方法与server交互(在url指定的jsp页面中,调用writer编写了xml文件并以responseXML返回给request);
(3)交互状态有变时会调用callback函数,callback判定状态,若交互成功则读取responseXML中的值;
(4)根据读取到的responseXML中的值动态生成innerHTML返回给页面。
二、代码
1.index.html
1 <html> 2 <head> 3 <script> 4 5 function validate(){ 6 var idField = document.getElementById("testBtn"); 7 var url = "validate.jsp?id="+escape(idField); 8 req = new XMLHttpRequest(); 9 req.open("GET", url, true); 10 req.onreadystatechange = callback; 11 req.send(null); 12 13 } 14 15 function callback(){ 16 if(req.readyState == 4){ 17 //alert(req.status); 18 //alert(req.responseXML); 19 //alert( msg); 20 if(req.status == 200){ 21 var msg = req.responseXML.getElementsByTagName("msg")[0]; 22 setMsg(msg.childNodes[0].nodeValue); 23 } 24 } 25 } 26 27 function setMsg(msg){ 28 var mdiv = document.getElementById("ajaxMsg"); 29 if(msg == "abc"){ 30 mdiv.innerHTML = "<div>America Born Chinese</div>"; 31 }else if(msg == "123"){ 32 mdiv.innerHTML = "<div>阿拉伯数字</div>"; 33 } 34 35 } 36 </script> 37 </head> 38 <body> 39 <input type="submit" id="testBtn" onclick="validate()" value="mybutton"/> 40 <span id="ajaxMsg"></span> 41 </body> 42 </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 %>
三、运行结果