You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中如何根据前一个下拉框值获取第二个下拉框值

实现Flask二级联动下拉框(根据客户名称获取实例名称)

嘿,作为Flask和编程新手,能搞定第一个下拉框已经很棒了!二级联动其实就是通过前端触发请求,后端根据选中的客户值过滤查询实例数据,再返回给前端更新第二个下拉框,咱们一步步来:

1. 后端新增API路由(处理实例数据查询)

首先你需要加一个专门的路由,用来接收前端传过来的选中客户名称,然后从数据库里过滤出对应的实例数据,再以JSON格式返回给前端。

假设你用SQLAlchemy做数据库操作(大部分Flask教程都会用它),代码大概是这样:

from flask import Flask, render_template, request, jsonify
from your_model_file import Customer, Instance  # 导入你的模型类

app = Flask(__name__)

# 你已经实现的加载第一个下拉框的路由
@app.route('/')
def index():
    customers = Customer.query.all()  # 获取所有客户
    return render_template('index.html', customers=customers)

# 新增的API:根据客户名称获取实例
@app.route('/get_instances')
def get_instances():
    # 获取前端传过来的选中客户名称
    selected_customer = request.args.get('customer_name')
    # 过滤查询:只查属于该客户的实例
    instances = Instance.query.filter_by(customer_name=selected_customer).all()
    # 把实例数据转成前端能处理的列表格式(比如包含id和name)
    instance_list = [{'id': inst.id, 'name': inst.instance_name} for inst in instances]
    # 返回JSON数据
    return jsonify(instance_list)

如果是用原生SQL查询的话,过滤条件可以这么写:

cursor.execute("SELECT id, instance_name FROM instances WHERE customer_name = %s", (selected_customer,))

2. 前端页面修改(实现联动逻辑)

在你的HTML模板里,给第一个下拉框添加onchange事件,触发JS函数去请求后端API,然后更新第二个下拉框的选项。

示例HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title>二级联动下拉框</title>
</head>
<body>
    <!-- 第一个下拉框:客户名称 -->
    <select id="customer_select" onchange="loadInstances()">
        <option value="">请选择客户</option>
        {% for customer in customers %}
            <option value="{{ customer.customer_name }}">{{ customer.customer_name }}</option>
        {% endfor %}
    </select>

    <!-- 第二个下拉框:实例名称 -->
    <select id="instance_select">
        <option value="">请先选择客户</option>
    </select>

    <script>
        function loadInstances() {
            // 获取选中的客户名称
            const customerName = document.getElementById('customer_select').value;
            const instanceSelect = document.getElementById('instance_select');

            // 如果没选客户,重置实例下拉框
            if (!customerName) {
                instanceSelect.innerHTML = '<option value="">请先选择客户</option>';
                return;
            }

            // 发送请求到后端API,处理特殊字符避免请求出错
            const encodedName = encodeURIComponent(customerName);
            fetch(`/get_instances?customer_name=${encodedName}`)
                .then(response => response.json())
                .then(data => {
                    // 清空实例下拉框现有选项
                    instanceSelect.innerHTML = '<option value="">请选择实例</option>';
                    // 循环添加新的实例选项
                    data.forEach(instance => {
                        const option = document.createElement('option');
                        option.value = instance.id;  // 可以用id或者name作为值
                        option.textContent = instance.name;
                        instanceSelect.appendChild(option);
                    });
                })
                .catch(error => console.error('加载实例失败:', error));
        }
    </script>
</body>
</html>

3. 关键注意点

  • 确保你的Instance模型(或者数据库表)里有customer_name字段,用来关联客户和实例,这样才能通过客户名称过滤实例。
  • 测试的时候可以打开浏览器的开发者工具(F12),查看Network标签页,检查请求是否成功、后端返回的数据是否正确。
  • 如果客户名称可能包含空格、特殊字符,一定要用encodeURIComponent处理后再拼到URL里,避免请求出错。

这样就能实现第一个下拉框选完客户后,第二个下拉框自动加载对应的实例啦!

内容的提问来源于stack exchange,提问作者S. G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:41:48