ajax案例-实现省市区三级联动

2023-04-11 08:27:29

效果:
在这里插入图片描述
数据表的设计:

CREATE TABLE `province_city_district` (
  `id` int(11) NOT NULL COMMENT '地区代码',
  `pid` int(11) DEFAULT NULL COMMENT '当前地区的上一级地区代码',
  `name` varchar(10) DEFAULT NULL COMMENT '地区名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='省市县数据表';

地区实体类:

public class Area {
    private int id;
    private String name;

    public Area() {
    }

    public Area(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>实现省市区三级联动</title>
<!--  引入自定义的jQuery库  -->
    <script type="text/javascript" src="js/jQuery-1.0.0.js"></script>
</head>
<body>
<script type="text/javascript">
    $(function (){
        $.ajax({
            type:"GET",
            url:"/ajax/listArea",
            data:"",
            async:true,
            success:function (jsonArr){
                var html = "<option value=\"\">-请选择省份-</option>"
                for (let i = 0; i < jsonArr.length; i++) {
                    html += "<option value='"+jsonArr[i].id+"'>"+jsonArr[i].name+"</option>"
                }
                $("#province").html(html)
            }
        })
        //只要value发生变换就发送ajax请求
        $("#province").change(function (){
            //alert(this)//[object HTMLSelectElement]
            // alert(this.value)
            $.ajax({
                type:"GET",
                url:"/ajax/listArea",
                data:"pid="+this.value,
                async:true,
                success:function (jsonArr){
                    var html = "<option value=\"\">-请选择市-</option>"
                    for (let i = 0; i < jsonArr.length; i++) {
                        html += "<option value='"+jsonArr[i].id+"'>"+jsonArr[i].name+"</option>"
                    }
                    $("#city").html(html)
                }
            })
        })

        /*$("#city").change(function (){
            //alert(this)//[object HTMLSelectElement]
            alert(this.value)
            $.ajax({
                type:"GET",
                url:"/ajax/listArea",
                data:"pid="+this.value,
                async:true,
                success:function (jsonArr){
                    var html = "<option value=\"\">-请选择区-</option>"
                    for (let i = 0; i < jsonArr.length; i++) {
                        html += "<option value='"+jsonArr[i].id+"'>"+jsonArr[i].name+"</option>"
                    }
                    $("#region").html(html)
                }
            })
        })*/
        //下面回顾一下使用ajax
        document.getElementById("city").onchange = function (){
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function (){
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        var html = "<option value=\"\">-请选择区-</option>"
                        var jsonArr = JSON.parse(this.responseText)
                        for (let i = 0; i < jsonArr.length; i++) {
                            html += "<option value='"+jsonArr[i].id+"'>"+jsonArr[i].name+"</option>"
                        }
                        document.getElementById("region").innerHTML = html
                    }
                }
            }
            //获取city的value
            var pid = this.value;
            alert(pid)
            xhr.open("GET","/ajax/listArea?pid="+pid,true)
            xhr.send()
        }
    })
</script>

<select id="province">

</select>
<select id="city">

</select>
<select id="region">

</select>
</body>
</html>

后端代码:

@WebServlet("/listArea")
public class ListAreaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pid = request.getParameter("pid");
        if (pid == null || pid.length() == 0){
            pid = "0";
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Area> areaList = new ArrayList();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"
                    , "root", "yg123");
            String sql = "select id,name from province_city_district where pid=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(pid));
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                Area area = new Area(id, name);
                areaList.add(area);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
        }
        response.setContentType("text/html;charset=UTF-8");
        String jsonArr = JSON.toJSONString(areaList);
        response.getWriter().write(jsonArr);
    }
}
  • 作者:小叶子学JAVA
  • 原文链接:https://blog.csdn.net/qq_55814328/article/details/125034264
    更新时间:2023-04-11 08:27:29