用自写的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. 展示效果

相关推荐
编程、小哥哥15 分钟前
互联网大厂Java求职面试实战:Spring Boot微服务架构及Kafka消息处理示例解析
java·spring boot·微服务·kafka·面试技巧
当归102415 分钟前
Fuse.js:打造极致模糊搜索体验
开发语言·javascript·ecmascript
難釋懷1 小时前
Vue-Todo-list 案例
前端·vue.js·list
前端达人1 小时前
React 播客专栏 Vol.18|React 第二阶段复习 · 样式与 Hooks 全面整合
前端·javascript·react.js·前端框架·ecmascript
GISer_Jing1 小时前
Monorepo 详解:现代前端工程的架构革命
前端·javascript·架构
magic 2451 小时前
return this;返回的是谁
java·开发语言
sg_knight2 小时前
Eureka 高可用集群搭建实战:服务注册与发现的底层原理与避坑指南
java·spring boot·spring·spring cloud·微服务·云原生·eureka
比特森林探险记2 小时前
Go Gin框架深度解析:高性能Web开发实践
前端·golang·gin
前端百草阁5 小时前
JavaScript 模块系统:CJS/AMD/UMD/ESM
javascript·ecmascript
打小就很皮...5 小时前
简单实现Ajax基础应用
前端·javascript·ajax