欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

jQuery+jsp实现省市县三级联动效果(附源码)_jquery

程序员文章站 2022-04-13 12:41:03
...
本文实例讲述了jQuery+jsp实现省市县三级联动效果的方法。分享给大家供大家参考,具体如下:

在这里,用MySQL数据库存储了全国所有的省市县地区信息(点击此处下载源代码)

使用过的jar包

google的Gson.jar
mysql-connector-java-5.1.13-bin.jar

将实验图贴出来:

jQuery+jsp实现省市县三级联动效果(附源码)_jquery

显示页面index.jsp





 省市区三级联动下拉菜单
省份: 城市: 区(县):

数据库交互GetDropdownDataServlet

public class GetDropdownDataServlet extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {
  doPost(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {
  String parentId = request.getParameter("parentId");
  if (parentId == null || parentId == "") {
   parentId = "0";
  }
  Connection conn = null;
  String json = "";
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager.getConnection("jdbc:mysql://localhost/dropdown",
     "root", "root");
   Statement stat = conn.createStatement();
   ResultSet rs = stat
     .executeQuery("select region_id,region_name from region where parent_id = "
       + parentId);
   ArrayList rsList = new ArrayList();
   Map map = null;
   while (rs.next()) {
    map = new HashMap();
    map.put("id", rs.getInt(1));
    map.put("name", rs.getString(2));
    rsList.add(map);
   }
   rs = null;
   Gson gson = new Gson();
   json = gson.toJson(rsList);
   System.out.println("json=" + json);
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   if (conn != null) {
    try {
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
  response.setCharacterEncoding("UTF-8");
  response.getWriter().print(json);
 }
}

希望本文所述对大家jQuery程序设计有所帮助。