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

如何将点击的<td>元素值传递给Flask中的Python函数?

实现点击表格<td>值传递到Flask后端函数的方法

要把前端点击<td>获取的值传给Flask的Python函数,核心是通过AJAX请求(比如用fetch API)把数据发送到后端路由。以下是具体实现步骤:

1. 修改前端JavaScript代码

把获取到的<td>值通过POST请求发送到Flask后端的指定路由:

var table = document.getElementById('mytable'),
  cells = table.getElementsByTagName('td');

for (var i = 0, len = cells.length; i < len; i++) {
  cells[i].onclick = function() {
    const tdValue = this.innerHTML;
    console.log(tdValue);
    
    // 发送请求到后端
    fetch('/receive-td-value', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({value: tdValue}),
    })
    .then(response => response.json())
    .then(data => {
      console.log('后端响应:', data);
      // 这里可以处理后端返回的结果,比如更新页面内容
    })
    .catch(error => {
      console.error('请求出错:', error);
    });
  }
}

2. 在Flask后端添加路由函数

创建对应的路由来接收前端发送的数据,并处理:

from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

# 渲染表格的页面路由
@app.route('/')
def index():
    # 这里替换成你实际的表格数据来源逻辑
    df_excel_data = [...]
    return render_template('your_template.html', df_excel_data=df_excel_data)

# 接收<td>值的处理路由
@app.route('/receive-td-value', methods=['POST'])
def receive_td_value():
    data = request.get_json()
    td_value = data.get('value')
    
    # 这里编写你对该值的业务处理逻辑,比如查询数据库、计算等
    print('收到前端传来的<td>值:', td_value)
    
    # 返回响应给前端
    return jsonify({'status': 'success', 'received_value': td_value})

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

3. 可选:优化HTML的点击事件绑定

你原HTML中给第一个<td>加了onclick="passvaluefun()",可以统一成直接在HTML中传入值调用函数,简化逻辑:

<table border=5 id="mytable">
  <thead>
    <td>Erp</td>
    <td>Status</td>
    <td>name</td>
    <td>Days</td>
  </thead>

  {% for tr in df_excel_data%}
    <tr>
      <!-- 给每个<td>绑定点击事件,直接传入当前单元格的值 -->
      <td onclick="sendValueToBackend('{{tr[0]}}')">{{tr[0]}}</td>
      <td onclick="sendValueToBackend('{{tr[1]}}')">{{tr[1]}}</td>
      <td onclick="sendValueToBackend('{{tr[2]}}')">{{tr[2]}}</td>
      <td onclick="sendValueToBackend('{{tr[3]}}')">{{tr[3]}}</td>
    </tr>
  {% endfor %}
</table>

<script>
function sendValueToBackend(value) {
  console.log(value);
  fetch('/receive-td-value', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({value: value}),
  })
  .then(response => response.json())
  .then(data => console.log('后端响应:', data))
  .catch(error => console.error('请求出错:', error));
}
</script>

关键说明

  • 前端发送JSON格式数据时,必须设置Content-Type为application/json,确保后端能正确解析
  • 后端用request.get_json()解析前端传来的JSON数据;若用GET请求,可通过URL参数传递值,后端用request.args.get('value')获取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:51:46