class="java" name="code">package com.lj.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lj.lingling.model.Person;
public class ResponseBody extends HttpServlet
{
Map<Integer, List<Person>> persons=new HashMap<Integer, List<Person>>();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/xml;charset=utf-8");
PrintWriter out = response.getWriter();
//获取部门id
int did=Integer.parseInt(request.getParameter("did"));
//获取用户列表对象
List<Person> ps=persons.get(did);
//拼接xml
StringBuffer px=new StringBuffer();
px.append("<persons>");
for(Person p:ps){
px.append("<id>").append(p.getId()).append("</id>");
px.append("<name>").append(p.getName()).append("</name>");
px.append("<age>").append(p.getAge()).append("</age>");
}
px.append("</persons>");
out.write(px.toString());
out.flush();
out.close();
}
public ResponseBody()
{
List<Person> list=new ArrayList<Person>();
list.add(new Person(1,"james",25));
list.add(new Person(2,"smith",22));
persons.put(1, list);
}
}
这里有一个关键的地方就是设置response的ContentType:
response.setContentType("text/xml;charset=utf-8");
这里把返回文本类型设置为text/xml,这样浏览器就会对文本内容进行xml的
解析,并显示在浏览器里。
然后是js的代码:
<script type="text/javascript">
window.onload=init;
function init(){
var btn=document.getElementById("getData");
btn.onclick=getData;
}
function getData(){
var xhr=new XMLHttpRequest();
console.log(xhr);
xhr.open("POST", "<%=path%>/servlet/ResponseBody?did=1", true);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
//console.log(xhr.responseText);
console.log(xhr.responseXML);
//获取person节点
var pns=xmlDoc.getElementsByTagName("persons");
// console.log(pns.length);
//遍历所有节点, 获取id,name, age
for(var i=0;i<pns.length;i++){
console.log((pns[i].getElementsByTagName("id"))[1].firstChild.nodeValue);
}
}
};
}
</script>
</head>
<body>
<input type="button" value="获取数据" id="getData"/>
<div id="serverData"></div>
</body>
</html>