日期:2014-05-16 浏览次数:20401 次
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); } }
<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>
response.setContentType("application/json;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("["); for(Person p:ps){ px.append("{"); px.append("id:").append(p.getId()).append(","); px.append("name:\"").append(p.getName()).append("\","); px.append("age:").append(p.getAge()).append("},"); } px.deleteCharAt(px.lastIndexOf(",")); px.append("]"); out.write(px.toString()); out.flush(); out.close();
function getData(){ var xhr=new XMLHttpRequest(); console.log(xhr); xhr.open("get", "<%=pat