AJAX解析json之 下拉框 二级联动

这个例子跟上次写的ajax解析xml实现的效果是一样的!

是实现省、市二级联动,当选择某一省时,改省下面的市就会在另一个下拉框显示出来。在本例中AJAX通过解析json文件得到的数据传回到jsp页面,其中省市均是从数据库取到的值:

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
  
  
  
    省:
    市:
  

servlet代码:
public class JsonGetP extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String province = request.getParameter("province");
		if (province != null) {
			sendCity(request, response, province);
		} else {
			ShengDao sd = new ShengDao();
			List list = sd.selAll();
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			response.setContentType("text/xml");
			out.print("[");
			for (Sheng sheng : list) {
				JSONObject jsonobj=JSONObject.fromObject(sheng);
				String str=jsonobj.toString();
				out.print(str+",");
				out.println();
			}
			out.print("]");
		}
	}

	public void sendCity(HttpServletRequest request,
			HttpServletResponse response, String shorter) {
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			response.setContentType("text/html");
			ShengDao sd = new ShengDao();
			out.print("[");
			List list = sd.selAll(shorter);
			for (City city : list) {
				JSONObject jsonobj=JSONObject.fromObject(city);
				String str=jsonobj.toString();
				out.print(str+",");
				out.println();
			}
			out.print("]");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(笔记)