欢迎来到福编程网,本站提供各种互联网专业知识!

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

发布时间:2013-11-14 作者: 来源:转载
实现盛市二级联动,当选择某一省时,改省下面的市就会在另一个下拉框显示出来,下面有个不错的示例,需要的朋友可以参考下
这个例子是实现盛市二级联动,当选择某一省时,改省下面的市就会在另一个下拉框显示出来。在本例中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+"/";
%>







省:<select name="sheng" id="sheng" onchange="getcity()">


市:<select name="city" id="city">





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();
}
}

相关推荐