You need to enable JavaScript to run this app. 如何在Flask中实现基于SQLite的带自动提交三级联动下拉菜单代码?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask中实现基于SQLite的带自动提交三级联动下拉菜单代码?

Flask 基于SQLite的三级联动下拉菜单实现

适配的SQLite表结构

直接匹配联动需求的表核心字段如下:

  • id:自增主键
  • node_name:下拉显示的文本内容(对应需求里的"ab"、"a"、"b"、"aa"、"aaa"等选项)
  • parent_id:父节点关联ID(根节点即一级菜单的parent_id=0,二级菜单关联所属一级菜单的id,三级菜单关联所属二级菜单的id)

后端 main.py 编写

from flask import Flask, render_template, request, jsonify
import sqlite3

app = Flask(__name__)
# 替换为实际的SQLite数据库文件路径
DB_FILE_PATH = "your_database.db"

def connect_db():
    conn = sqlite3.connect(DB_FILE_PATH)
    conn.row_factory = sqlite3.Row
    return conn

# 主页路由,渲染下拉页面
@app.route('/')
def show_dropdown_page():
    conn = connect_db()
    # 初始化加载所有一级菜单选项(根节点)
    level1_nodes = conn.execute("SELECT id, node_name FROM dropdown_node WHERE parent_id = 0").fetchall()
    conn.close()
    return render_template("output.html", level1_nodes=level1_nodes)

# 联动数据接口,根据选中的父节点返回对应子级选项
@app.route("/get_sub_options")
def get_sub_options():
    parent_node_id = request.args.get("parent_id", type=int)
    conn = connect_db()
    child_nodes = conn.execute(
        "SELECT id, node_name FROM dropdown_node WHERE parent_id = ?",
        (parent_node_id,)
    ).fetchall()
    conn.close()
    # 转换为前端可解析的JSON格式
    sub_option_list = [{"id": row["id"], "option_text": row["node_name"]} for row in child_nodes]
    return jsonify(sub_option_list)

# 表单提交处理
@app.route("/submit_selection", methods=["POST"])
def handle_submit():
    selected_l1 = request.form.get("level1")
    selected_l2 = request.form.get("level2")
    selected_l3 = request.form.get("level3")
    # 此处可添加自定义提交后业务逻辑,如查询结果、写入数据等
    return f"已提交选择:一级={selected_l1}, 二级={selected_l2}, 三级={selected_l3}"

if __name__ == "__main__":
    app.run(debug=True)

前端 output.html 编写

该文件需放置在Flask项目的templates目录下,核心实现选中后自动联动加载下级选项、带提交按钮的逻辑:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>三级联动下拉</title>
</head>
<body>
    <form action="/submit_selection" method="post">
        <div style="margin: 10px 0;">
            <label>一级菜单:</label>
            <select name="level1" id="level1">
                <option value="">请选择</option>
                {% for node in level1_nodes %}
                <option value="{{ node.id }}">{{ node.node_name }}</option>
                {% endfor %}
            </select>
        </div>

        <div style="margin: 10px 0;">
            <label>二级菜单:</label>
            <select name="level2" id="level2">
                <option value="">请选择</option>
            </select>
        </div>

        <div style="margin: 10px 0;">
            <label>三级菜单:</label>
            <select name="level3" id="level3">
                <option value="">请选择</option>
            </select>
        </div>

        <div style="margin: 20px 0;">
            <button type="submit">提交选择</button>
        </div>
    </form>

    <script>
        const l1Select = document.getElementById('level1');
        const l2Select = document.getElementById('level2');
        const l3Select = document.getElementById('level3');

        // 通用联动加载函数
        async function loadChildOptions(parentSelectEl, targetSelectEl, parentNodeId) {
            // 清空目标下拉的原有选项
            targetSelectEl.innerHTML = '<option value="">请选择</option>';
            if (!parentNodeId) return;

            // 请求后端获取子级选项
            const response = await fetch(`/get_sub_options?parent_id=${parentNodeId}`);
            const childOptions = await response.json();

            // 渲染子选项到目标下拉框
            childOptions.forEach(item => {
                const optEl = document.createElement('option');
                optEl.value = item.id;
                optEl.textContent = item.option_text;
                targetSelectEl.appendChild(optEl);
            })
        }

        // 一级菜单选中,联动加载二级选项,同时清空三级选项
        l1Select.addEventListener('change', () => {
            loadChildOptions(l1Select, l2Select, l1Select.value);
            l3Select.innerHTML = '<option value="">请选择</option>';
        })

        // 二级菜单选中,联动加载三级选项
        l2Select.addEventListener('change', () => {
            loadChildOptions(l2Select, l3Select, l2Select.value);
        })
    </script>
</body>
</html>

需求匹配说明

完成SQLite数据配置后,可直接实现指定联动效果:

  • 一级菜单选中ab节点时,接口将返回该节点下挂载的a、b两个二级选项
  • 二级菜单选中a节点时,接口将返回该节点下挂载的aa、aaa两个三级选项
  • 所有选项无硬编码,完全从SQLite数据库读取,后续新增节点无需修改前后端代码

内容的提问来源于stack exchange,提问作者Snehal Sawant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 12:45:07