将按钮按下与表格行Flask/Python关联



我在index.html:中有这个

{% for item in data %}
<tr>
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
<td>{{item[2]}}</td>
<td>{{item[3]}}</td>
<td>{{item[4]}}</td>
<td>{{item[5]}}</td>
<td>{{item[6]}}</td>
<td>{{item[7]}}</td>
<td>{{item[8]}}</td>
<td>{{item[9]}}</td>
<td>{{item[10]}}</td>
<td>
<form action="{{ url_for('history') }}" method="POST">
<button type="submit"> History </button>
</form>
</td>
</tr>
{% endfor %}

这个在app.py中:

@app.route('/history', methods=['GET', 'POST'])
def history():
return render_template('history.html')

所以我的网页有一个表,里面有很多行,每一行都是一个标有"历史记录"的按钮。既然现在每个按钮都做相同的事情,并指向history((,我如何区分原始点击来自哪行数据?

您必须将项目ID添加到HTML表单中,但不能显示它。https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden

类似以下

<form action="{{ url_for('history') }}" method="POST">
<input id="historicalId" name="historicalId" type="hidden" value="{{item.id}}">
<button type="submit"> History </button>
</form>

然后在烧瓶中,您需要解析出请求表单主体

我写这个答案是因为它可能会对某人有所帮助。检查每个表行是否显示一本书,并且表行末尾有一个编辑按钮。

{% for book in books %}
<tr>
<td>{{ book[1] }}</td>
<td>{{ book[2] }} </td>
<td>{{ book[3] }} </td>
<td>{{ book[4] }} </td>
<input id="book_id" name="book_id"
type="hidden" value="{{ book[0] }}">
<td><button type="submit" name="edit" value="{{ book[0] }}"
formmethod="post">Edit</button></td>
</tr>

每一行都有一个隐藏的book_id,用于使用以下代码在后端检索书籍:

if request.form.get("edit"):
print('Book ID: ', request.form.get('edit'))

最新更新