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

如何将MDBootstrap表格选中行的字段值传递到Flask后端views.py

实现步骤

1. 前端页面修改

首先添加触发提交的按钮,你可以放在表格的上方或者任意你想要的位置:

<button id="submitSelected" class="btn btn-primary mb-2">提交选中行数据</button>

然后修改原有JS代码,新增选中数据提交的逻辑:

<script>
  $('#persons_table').mdbEditor({
    modalEditor: true,
    headerLength: 6,
  });
  $('.dataTables_length').addClass('bs-select');

  // 新增选中行提交逻辑
  $('#submitSelected').on('click', function() {
    // 获取选中的行
    const selectedRow = $('tr.tr-color-selected');
    // 未选中的提示
    if (selectedRow.length === 0) {
      alert('请先选中一行数据再提交');
      return;
    }
    // 提取行内字段
    const submitData = {
      example_name: selectedRow.find('td:eq(1)').text().trim(),
      example_phone: selectedRow.find('td:eq(2)').text().trim(),
      example_email: selectedRow.find('td:eq(3)').text().trim()
    };
    // 发送请求到Flask后端
    $.ajax({
      url: '/receive-selected-data',
      method: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(submitData),
      success: function(res) {
        if (res.code === 200) {
          alert('数据提交成功');
          // 可自行添加后续操作,比如刷新表格、关闭弹窗等
        }
      },
      error: function() {
        alert('提交失败,请检查网络后重试');
      }
    })
  })
</script>

2. 后端Flask逻辑编写

在你的views.py中添加对应的接收接口:

from flask import request, jsonify
# 导入你自己的db和模型类,示例如下:
# from app import db
# from app.models import YourModel

@app.route('/receive-selected-data', methods=['POST'])
def receive_selected_data():
    # 接收前端传的JSON数据
    req_data = request.get_json()
    # 提取对应字段
    example_name = req_data.get('example_name')
    example_phone = req_data.get('example_phone')
    example_email = req_data.get('example_email')

    # 这里替换为你自己的业务逻辑,比如数据入库、查询处理等
    # 示例入库逻辑:
    # new_data = YourModel(
    #     name=example_name,
    #     phone=example_phone,
    #     email=example_email
    # )
    # db.session.add(new_data)
    # db.session.commit()

    # 返回响应给前端
    return jsonify({
        "code": 200,
        "msg": "数据接收成功"
    })

可选说明

  • 如果你的表格支持多选,只需要把获取选中行的逻辑改成遍历$('tr.tr-color-selected'),把所有行的数据拼成数组传给后端即可
  • 如果不需要无刷新提交,也可以构造隐藏表单动态赋值后触发表单提交,效果和AJAX一致只是会刷新页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:39:01