日期:2014-05-16  浏览次数:20401 次

javascript获取后台传送的xml类型数据以及json类型数据
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>



========================================================================

接下来是json数据类型

首先在servlet里面通过PrintWriter写入数据。
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();



页面里的js代码如下:
function getData(){
			 var xhr=new XMLHttpRequest();
			 console.log(xhr);
			 xhr.open("get", "<%=pat