AJAX案例三:处理XML响应
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <meta http-equiv="pragma" content="no-cache"> 7 <meta http-equiv="cache-control" content="no-cache"> 8 <meta http-equiv="expires" content="0"> 9 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 10 <meta http-equiv="description" content="This is my page"> 11 <script type="text/javascript"> 12 function createXMLHttpRequest() { 13 try { 14 return new XMLHttpRequest(); 15 } catch (e) { 16 try { 17 return ActvieXObject("Msxml2.XMLHTTP"); 18 } catch (e) { 19 try { 20 return ActvieXObject("Microsoft.XMLHTTP"); 21 } catch (e) { 22 alert("用的是什么浏览器啊?"); 23 throw e; 24 } 25 } 26 } 27 } 28 window.onload = function() { 29 var btn = document.getElementById("btn"); 30 btn.onclick = function() { 31 var xmlHttp = createXMLHttpRequest(); 32 xmlHttp.open("GET", "<c:url value='/AServlet'/>", true); 33 xmlHttp.send(null); 34 xmlHttp.onreadystatechange = function() { 35 if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { 36 //改成XML 37 var doc = xmlHttp.responseXML; 38 var age,name; 39 //DOM解析 40 var stu=doc.getElementsByTagName("student")[0]; 41 if(window.addEventListener) { 42 name=stu.getElementsByTagName("name")[0].textContent;//其他浏览器 43 age=stu.getElementsByTagName("age")[0].textContent; 44 } else { 45 name=stu.getElementsByTagName("name")[0].text;//IE支持 46 age=stu.getElementsByTagName("age")[0].text; 47 } 48 var text = "姓名:"+name+",年龄:"+age; 49 var h1=document.getElementById("h1"); 50 h1.innerHTML = text; 51 } 52 }; 53 }; 54 }; 55 </script> 56 </head> 57 <body> 58 <button id="btn">点击这里</button> 59 <h1 id="h1"></h1> 60 </body> 61 </html>
1 import java.io.IOException; 2 import javax.servlet.ServletException; 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 public class AServlet extends HttpServlet { 7 public void doGet(HttpServletRequest request, HttpServletResponse response) 8 throws ServletException, IOException { 9 //改成xml 10 response.setContentType("text/xml;charset=utf-8"); 11 request.setCharacterEncoding("UTF-8"); 12 String s= "<student>" + 13 "<name>张三</name>" + 14 "<age>18</age>" + 15 "</student>"; 16 response.getWriter().print(s); 17 } 18 }