js_ajax简单例子_基于json的实现

@WebServlet("/ajax.do")
public class HelloAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static Map<Integer, List<Person>> personMap=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloAjax() {
        super();
        // TODO Auto-generated constructor stub
        personMap=new HashMap<>();
        List<Person> ps=new ArrayList<>();
        ps.add(new Person(1, "1xm1", "男", 150.8));
        ps.add(new Person(2, "1xm2", "男", 150.9));
        ps.add(new Person(3, "1xm3", "男", 160.8));
        ps.add(new Person(4, "1xm4", "男", 170.8));
        personMap.put(1, ps);
        
        ps=new ArrayList<>();
        ps.add(new Person(1, "2xm1", "男", 250.8));
        ps.add(new Person(2, "2xm2", "男", 250.9));
        ps.add(new Person(3, "2xm3", "男", 260.8));
        ps.add(new Person(4, "2xm4", "男",270.8));
        personMap.put(2, ps);
        
        ps=new ArrayList<>();
        ps.add(new Person(1, "3xm1", "男", 350.8));
        ps.add(new Person(2, "3xm2", "男", 350.9));
        ps.add(new Person(3, "3xm3", "男", 360.8));
        ps.add(new Person(4, "3xm4", "男", 370.8));
        personMap.put(3, ps);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		int depid=Integer.parseInt(request.getParameter("dep"));
		List<Person> ps=personMap.get(depid);
		StringBuffer xml=new StringBuffer();
		xml.append("[");
		int index=0;
		for(Person p:ps) {
			if(index==0) {
				xml.append("{");
			}else {
				xml.append(",{");
			}
			index++;
			xml.append("id:").append(p.getId()).append(",");
			xml.append("name:\"").append(p.getName()).append("\",");
			xml.append("sex:\"").append(p.getSex()).append("\",");
			xml.append("salary:\"").append(p.getSalary()).append("\"");
			xml.append("}");
		}
		xml.append("]");
	    response.getWriter().write(xml.toString());
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload=init;
function init(){
	var deps=document.getElementById("dep");
    deps.onchange=getdata;
}
function getdata(){
	var value=this.value;
	var xtr;
	if (window.XMLHttpRequest) 
	  {// code for IE7+, Firefox, Chrome, Opera, Safari 
		xtr=new XMLHttpRequest(); 
	  } 
	else 
	  {// code for IE6, IE5 
		xtr=new ActiveXObject("Microsoft.XMLHTTP"); 
	  }
	xtr.open("post","ajax.do",true);
	xtr.onreadystatechange=function(){
		if(xtr.readyState==4&&xtr.status==200){
			var jsonDoc=xtr.responseText;
			var ps=eval(jsonDoc);
			var str="";
			for(var i=0;i<ps.length;i++){
				str+=ps[i].id+"----"+ps[i].name+"----"+ps[i].sex+"----"+ps[i].salary+"<br>";
			}
			document.getElementById("display").innerHTML=str; 
		}
	}
	xtr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
	xtr.send("dep="+value);
	
	
}
</script>
</head>
<body>
<input type="button" id="btn" value="测试">
<select id="dep">
<option value="1">技术部1</option>
<option value="2">技术部2</option>
<option value="3">技术部3</option>
</select>
<div id="display"></div>
</body>
</html>

注意:(1).使用json,需要设置“text/html;charset=utf-8”

(2).json格式 [{,},{,}],在引号内若想再引入引号,需要用\"

(3).responseText返回的是json字符串,若想变为对象数组,需要使用eval()

猜你喜欢

转载自blog.csdn.net/HZPHYT/article/details/81183594