无数据库级联下拉列表

极客园地 2015-03-11

JQuery的AJAX一直不太清楚,借个机会,做了个小demo,记录:

页面显示:area.jsp

<div id="area">
	 <select id="area_first" onchange="ajax()">
	 	<option value=-1>--请选择--</option>
	 	<option value="1">北京</option>
	 	<option value="2">黑龙江</option>
	 </select>
	 <select id="area_second">
	 	<option value="-1">--请选择--</option>
	 </select>
 </div>

页面上的JS:

function ajax(){
		var firstValue = $("#area_first").children('option:selected').val();
		if(firstValue != -1){
			$.post("AreaServlet",{"firstValue":firstValue},function(data,textStauts){
				var html ="<option value='-1'>---请选择---</option>";
				var _json = eval(data);
				var json = _json[0];
				for(var i = 0; i < json.area.length; i++){
					alert(json.area[i].area_id);
					html += "<option id="+json.area[i].area_id+">"+json.area[i].area_name+"</option>";
				}
				$("#area_second").empty();
				$("#area_second").html(html);
			});
		}
	}

控制层的Servlet:AreaServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String firstValue = request.getParameter("firstValue");
		System.out.println(firstValue);
		if("2".equals(firstValue)){
			ArrayList<Area> objectTypes = new ArrayList<Area>();
			objectTypes.add(new Area("1", "大庆"));
			objectTypes.add(new Area("2", "哈尔滨"));
			objectTypes.add(new Area("3", "佳木斯"));
			
			JSONObject jsonObject = new JSONObject();
	        jsonObject.put("area", objectTypes);
	        
	        JSONArray jsonArray = new JSONArray();
	        jsonArray.add(jsonObject);
			System.out.println(jsonArray);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write(jsonArray.toString());
		}
	}

Area.java

package com.zsy.action;

public class Area {
	
	private String area_id;
	private String area_name;
	
	public String getArea_id() {
		return area_id;
	}
	public void setArea_id(String area_id) {
		this.area_id = area_id;
	}
	public String getArea_name() {
		return area_name;
	}
	public void setArea_name(String area_name) {
		this.area_name = area_name;
	}
	public Area(String area_id, String area_name) {
		super();
		this.area_id = area_id;
		this.area_name = area_name;
	}
	
	
}

相关推荐