【JavaScript&jQuery】省市区三级联动

HTML:

<%@page import="com.mysql.jdbc.Connection"%>
<%@ page language="java" import="java.util.*,com.ajax.connection.ConnectionUtil" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML>
<html>
  <head>
    <title>ajax-省市区级联</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <style type="text/css">
        *{padding:0px;margin:0px}
        body{font-family: "微软雅黑";font-size:14px;}
        fieldset{padding:80px; 485px;margin: 100px auto;border-radius:8px;}
        #province,#city,#area{padding:6px;120px;}
    </style>
    <script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
  </head>
  <body>
        <%
            List<HashMap<String,Object>> maps = ConnectionUtil.findProvinces();
            pageContext.setAttribute("provinces", maps);
        %>
        
        <fieldset>
            <legend>省市区三级联动</legend>
                省份:
                <select id="province" onchange="select_citys(this)">
                    <option value="">-请选择-</option>
                    <!-- 循环显示所有省份 -->
                    <c:forEach var="pv" items="${provinces}">
                        <option value="${pv.id}">${pv.name}</option>
                    </c:forEach>
                </select>
                城市:
                <select id="city" onchange="select_areas(this)">
                    <option value="">-请选择-</option>
                </select>
                区域:
                <select id="area">
                    <option value="">-请选择-</option>
                </select>
        </fieldset>
        
    <script type="text/javascript">
        //通过省份ID查询查询所有的城市信息
        function select_citys(obj){
            var provinceId = $(obj).val();
            if(!provinceId)return; // 声明变量就要判断是否为null
            $.ajax({
                type:"post",//请求方式get/post
                url:"${ctx}/CityServlet",//请求对应的地址
                data:{"provinceId":provinceId},//往服务器传递的参数,
                success:function(data){//服务器交互成功调用的回调函数,data就是服务器端传递出来的数据
                    var jdata = data.trim(); // 去前后空格
                    if(jdata=="fail"){
                        alert("查询失败!");
                    }else{
                        var jsonData = eval(jdata);//将字符串的json对象转换成json
                        $("#area").html("<option>-请选择-</option>");
                        append_template(jsonData,"city");
                    }
                }
            });
        };
             
        //通过省份ID查询查询所有的城市信息
        function select_areas(obj){
            var cityId = $(obj).val();
            if(!cityId)return;
            $.ajax({
                type:"post",
                url:"${ctx}/AreaServlet",
                data:{"cityId":cityId},
                success:function(data){
                    var jdata = data.trim();
                    if(jdata=="fail"){
                        alert("查询失败!");
                    }else{
                        var jsonData = eval(jdata);
                        append_template(jsonData,"area");
                    }
                }
            });
        };
             
        //封装其通用内容
        function append_template(jsonData,target){
            var length = jsonData.length;
            var html = "<option>-请选择-</option>";
            for(var i=0;i<length;i++){
                html +="<option value='"+jsonData[i].id+"'>"+jsonData[i].name+"</option>";
            }
            $("#"+target).html(html);
        };
    </script>
  </body>
</html>

过滤器:

package com.ajax.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CharacterFilter implements Filter {
    
    private FilterConfig config;
    
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
       
        String encoding = config.getInitParameter("encoding");
       
        if (encoding != null) {
           
            response.setContentType("text/html ;charset=" + encoding);
            
            request.setCharacterEncoding(encoding);
           
            response.setCharacterEncoding(encoding);
        }
        
        chain.doFilter(request, response);
    }
    
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }
    public void destroy() {
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ajaxDemo</display-name>
    <!-- 字符编码集拦截器 -->
    <filter>
        <filter-name>CharacterFilter</filter-name>
        <filter-class>com.ajax.filter.CharacterFilter</filter-class>
        <!-- 配置初始化参数 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <!-- 映射路径 -->
    <filter-mapping>
        <filter-name>CharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>pages/province.jsp</welcome-file>
    </welcome-file-list>
</web-app>

控制层代码:

package com.ajax.dao;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import com.ajax.connection.ConnectionUtil;

@WebServlet("/AreaServlet")
public class AreaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String cid = request.getParameter("cityId");
        if (cid != null && !cid.equals("")) {
            int cityId = Integer.parseInt(cid);
            List<HashMap<String, Object>> areas = ConnectionUtil
                    .findAreas(cityId);
            try {
                out.print(JSONUtil.serialize(areas));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            out.print("fail");
        }
    }

}
package com.ajax.dao;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import com.ajax.connection.ConnectionUtil;

@WebServlet("/CityServlet")
public class CityServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        
        String pid = request.getParameter("provinceId");
        if (pid != null && !pid.equals("")) {
            int provinceId = Integer.parseInt(pid);
            List<HashMap<String, Object>> citys = ConnectionUtil
                    .findCitys(provinceId);
            try {
                
                out.print(JSONUtil.serialize(citys));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            
            out.print("fail");
        }
    }

}

持久层代码:

package com.ajax.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ConnectionUtil {

    private static String url = "jdbc:mysql://localhost:3306/estore";
    private static String username = "root";
    private static String password = "f111111";
    
    public static Connection getConnection(){
        Connection connection = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url,username,password);
            return connection;
        }catch(Exception ex){
            return null;
        }
    }
    
    public static List<HashMap<String, Object>> findProvinces(){
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        List<HashMap<String, Object>> maps = null;
        try{
            String sql = "SELECT id,province FROM tm_province order by sort asc";
            connection = getConnection();
            statement = connection.createStatement();
            rs = statement.executeQuery(sql);
            maps = new ArrayList<HashMap<String,Object>>();
            HashMap<String, Object> map = null;
            while(rs.next()){
                map = new HashMap<String, Object>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("province"));
                maps.add(map);
            }
            return maps;
        }catch(SQLException sql){
            sql.printStackTrace();
            return null;
        }finally{
            try{
                if(rs!=null)rs.close();
                if(statement!=null)statement.close();
                if(connection!=null)connection.close();
            }catch(SQLException sql){
                sql.printStackTrace();
            }
        }
    }
    
    public static List<HashMap<String, Object>> findCitys(int provinceId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        List<HashMap<String, Object>> maps = null;
        try{
            String sql = "SELECT id,city FROM tm_city WHERE province_id = ?";
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            statement.setInt(1, provinceId);
            rs = statement.executeQuery();
            maps = new ArrayList<HashMap<String,Object>>();
            HashMap<String, Object> map = null;
            while(rs.next()){
                map = new HashMap<String, Object>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("city"));
                maps.add(map);
            }
            return maps;
        }catch(SQLException sql){
            sql.printStackTrace();
            return null;
        }finally{
            try{
                if(rs!=null)rs.close();
                if(statement!=null)statement.close();
                if(connection!=null)connection.close();
            }catch(SQLException sql){
                sql.printStackTrace();
            }
        }
    }
    
    public static List<HashMap<String, Object>> findAreas(int cityId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        List<HashMap<String, Object>> maps = null;
        try{
            String sql = "SELECT id,area FROM tm_area WHERE city_id = ?";
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            statement.setInt(1, cityId);
            rs = statement.executeQuery();
            maps = new ArrayList<HashMap<String,Object>>();
            HashMap<String, Object> map = null;
            while(rs.next()){
                map = new HashMap<String, Object>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("area"));
                maps.add(map);
            }
            return maps;
        }catch(SQLException sql){
            sql.printStackTrace();
            return null;
        }finally{
            try{
                if(rs!=null)rs.close();
                if(statement!=null)statement.close();
                if(connection!=null)connection.close();
            }catch(SQLException sql){
                sql.printStackTrace();
            }
        }
    }
    
}

原文地址:https://www.cnblogs.com/dflmg/p/6385722.html