用自写的jQuery库+Ajax实现了省市联动

  1. 省市联动:在网页上,选择对应的省份之后,动态的关联出该省份对应的市。选择对应的市之后,动态地关联出城市对应的区。

  2. 设计数据库表

    t_area (区域表)
    id(PK-自增) code name pcode

    1 001 河北省 null
    2 002 河南省 null
    3 003 石家庄 001
    4 004 邯郸 001
    5 005 郑州 002
    6 006 洛阳 002
    7 007 江苏 null
    8 008 南京 007

    将全国所有的省、市、区、县等信息都存储到一张表当中。
    采用的存储方式实际上是code pcode形势。

  3. 这里只是一个模拟,所以建的数据库是不完整的,想要完整的数据库,可以去网上找。

  4. 上代码

(1)自写的jQquery库

javascript 复制代码
function jQuery(selector){ // selector可能是#id,也可以是其他的选择器,例如类选择器:.class
    if(typeof selector == "string"){
        if (selector.charAt(0) == '#') {
            domObj = document.getElementById(selector.substring(1));
            return new jQuery();
        }
    }
    if(typeof selector == "function"){
        window.onload = selector;
    }
    this.html = function(htmlStr){
        domObj.innerHTML = htmlStr;
    }
    this.click = function(fun){
        domObj.onclick = fun;
    }
    this.val = function(v){
        if (v == undefined) {
            return domObj.value;
        }else{
            domObj.value = v;
        }
    }
    this.change = function(fun){
        domObj.onchange = fun;
    }
    // 静态的方法:发送ajax请求
    jQuery.ajax = function(jsonArgs){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (this.readyState == 4) {
                if (this.status == 200) {
                    var jsonObj = JSON.parse(this.responseText);
                    jsonArgs.success(jsonObj);
                }
            }
        }
        if (jsonArgs.type.toUpperCase() == "POST") {
            xhr.open("POST",jsonArgs.url,jsonArgs.async);
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
            xhr.send(jsonArgs.data);
        }
        if (jsonArgs.type.toUpperCase() == "GET") {
            xhr.open("GET",jsonArgs.url + "?" + jsonArgs.data,jsonArgs.async);
            xhr.send();
        }
    }
}
$=jQuery;

(2)html文件(Ajax请求)

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用ajax实现省市联动</title>
</head>
<body>
<!--引入自己编写的jQuery库-->
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script>
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<script type="text/javascript">
$(function(){
    // 发送ajax请求,获取所有的省份,省份的pcode是null
    $.ajax({
        type: "get",
        url : "/ajax/listArea",
        data : "t=" + new Date().getTime(),
        async : true,
        success:function(jsonArr){
            var html = "<option value=\"\">--请选择省份--</option>";
            for (var i = 0; i < jsonArr.length; i++) {
                var area = jsonArr[i];
                html += "<option value=\""+area.code+"\">"+area.name+"</option>"
            }
            $("#province").html(html)
        }
    })
    // 只要change发生,就发送ajax请求
    $("#province").change(function(){
        $.ajax({
            type: "get",
            url : "/ajax/listArea",
            data : "t=" + new Date().getTime()+ "&pcode="+this.value,
            async : true,
            success:function(jsonArr){
                var html = "<option value=\"\">--请选择市--</option>";
                for (var i = 0; i < jsonArr.length; i++) {
                    var area = jsonArr[i];
                    html += "<option value=\""+area.code+"\">"+area.name+"</option>"
                }
                $("#city").html(html)
            }
        })
    })
})
</script>
<select id="province"></select>
<select id="city"></select>
</body>
</html>

(3)servlet文件(后端)

java 复制代码
package com.bjpowernode.ajax.servlet;

import com.alibaba.fastjson.JSON;
import com.bjpowernode.ajax.bean.Area;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

/**
 * 动态获取所有的省份
 */
@WebServlet("/listArea")
public class ListAreaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 连接数据库,获取所有的对应区域,最终响应一个JSON格式的字符串给WEB前端
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs= null;
        ArrayList<Area> areas = new ArrayList<>();
        String pcode = request.getParameter("pcode");
        String sql;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";
            String user = "root";
            String password = "1234";
            conn = DriverManager.getConnection(url,user,password);
            if (pcode == null){
                sql = "select code,name from t_area where pcode is null";
                ps = conn.prepareStatement(sql);
            }else{
                sql = "select code,name from t_area where pcode = ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1,pcode);
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                String code = rs.getString("code");
                String name = rs.getString("name");
                Area area = new Area(code, name);
                areas.add(area);
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally{
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        response.setContentType("text/html,charset=UTF-8");
        String json = JSON.toJSONString(areas);
        response.getWriter().print(json);
    }

}
  1. 展示效果

相关推荐
万少13 小时前
Trae AI 编辑器6大使用规则
前端·javascript·人工智能
Lisonseekpan13 小时前
为什么要避免使用 `SELECT *`?
java·数据库·后端·sql·mysql·oracle
一只小透明啊啊啊啊13 小时前
Java的中间件
java·开发语言·中间件
Wilson Chen13 小时前
深入理解 MySQL 事务与锁机制:从 ACID 到 Next-Key Lock 的实证之旅
java·数据库·mysql
好玩的Matlab(NCEPU)13 小时前
如何编写 Chrome 插件(Chrome Extension)
前端·chrome
Yan-英杰13 小时前
Deepseek大模型结合Chrome搜索爬取2025AI投资趋势数据
前端·chrome
学编程就要猛13 小时前
数据结构初阶:Java中的ArrayList
java·开发语言·数据结构
JH307313 小时前
10分钟理解泛型的通配符(extends, super, ?)
java·开发语言·windows
Crystal32813 小时前
app里video层级最高导致全屏视频上的操作的东西显示不出来的问题
前端·vue.js
weixin_4454766813 小时前
Vue+redis全局添加水印解决方案
前端·vue.js·redis