AJAX案例三:处理XML响应

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return ActvieXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return ActvieXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("用的是什么浏览器啊?");
throw e;
}
}
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
var xmlHttp = createXMLHttpRequest();
xmlHttp.open("GET", "<c:url value='/AServlet'/>", true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//改成XML
var doc = xmlHttp.responseXML;
var age,name;
//DOM解析
var stu=doc.getElementsByTagName("student")[0];
if(window.addEventListener) {
name=stu.getElementsByTagName("name")[0].textContent;//其他浏览器
age=stu.getElementsByTagName("age")[0].textContent;
} else {
name=stu.getElementsByTagName("name")[0].text;//IE支持
age=stu.getElementsByTagName("age")[0].text;
}
var text = "姓名:"+name+",年龄:"+age;
var h1=document.getElementById("h1");
h1.innerHTML = text;
}
};
};
};
</script>
</head>
<body>
<button id="btn">点击这里</button>
<h1 id="h1"></h1>
</body>
</html>
 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//改成xml
response.setContentType("text/xml;charset=utf-8");
request.setCharacterEncoding("UTF-8");
String s= "<student>" +
"<name>张三</name>" +
"<age>18</age>" +
"</student>";
response.getWriter().print(s);
}
}
上一篇:Service 之间如何通信?- 每天5分钟玩转 Docker 容器技术(101)


下一篇:编写webpack 插件