AJAX解析XML实例之下拉框省、市二级联动

这个例子是实现省、市二级联动,当选择某一省时,改省下面的市就会在另一个下拉框显示出来。在本例中AJAX通过解析XML文件得到的数据传回到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 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.println("");
out.println("");
for (Sheng sheng : list) {
out.print(""+sheng.getProvince()+"");
out.println();
}
out.println("
");
}
}

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/xml");
ShengDao sd=new ShengDao();
List list=sd.selAll(shorter);
out.println("");
out.println("");
for (City city : list) {
out.println(""+city.getCityname()+"");
System.out.println(""+city.getCityname()+"");
}
out.println("
");
} catch (IOException e) {
e.printStackTrace();
}
}

你可能感兴趣的:(AJAX解析XML实例之下拉框省、市二级联动)