gpt4 book ai didi

python - 如何在 Flask 中按下按钮时获取 HTML 标签?

转载 作者:行者123 更新时间:2023-12-01 01:33:02 24 4
gpt4 key购买 nike

我的 HTML 模板有一个在浏览器上看起来像这样的表单:

enter image description here

当用户按下“oranges”旁边的“Select”按钮时,我想在Python中获取字符串“oranges”。

这是我的表单的样子:

<form action="{{url_for('select')}}" method="POST">
<div class="available_flights">
{% for product in [["A100", "oranges"], ["A101", "apples"]] %}
<td name = {{product[0]}} > {{product[1]}} {% include select_button ignore missing %} </td><br>
{% endfor %}
</div>
</form>

尝试 request.form["A100"] 返回错误请求错误。有没有办法获得这样的 tr 标签值?

最佳答案

您可以为要显示的每个项目创建唯一的 ID。每个td 及其相应的按钮在id 中都会有一个尾随数字,可用于在单击按钮时获取所需的文本。此外,在这种情况下,使用 jqueryajax 与后端通信会更简单:

在 HTML 中:

flights.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<div class='available_flights'>
{%for row in data%}
<td id='listing{{row.id}}' class='{{row.flight}}'>{{row.name}}</td>
<button id = 'button{{row.id}}' class='select_td'>Select</button>
<div id='info{{row.id}}'></div>
{%endfor%}
</div>
<script>
$(document).ready(function(){
$('.available_flights').on('click', '.select_td', function(){
var _id = this.id.match('\\d+');
var flight_name = $('#listing'+_id).text();
var abbrev = $('#listing'+_id).attr('class');
$.ajax({
url: "/get_flight",
type: "get",
data: {flight: flight_name, id:_id, name:abbrev},
success: function(response) {
$("#info"+_id).html(response.result);
}
});
});
});
</script>
</html>

然后,在应用程序中:

import flask, typing
app = flask.Flask(__name__)

class Flight(typing.NamedTuple):
id:int
flight:str
name:str

@app.route('/', methods=['GET'])
def home():
d = [["A100", "oranges"], ["A101", "apples"]]
return flask.render_template('flights.html', data=[Flight(i, a, b) for i, [a, b] in enumerate(d)])

@app.route('/get_flight')
def get_flight():
d = [["A100", "oranges"], ["A101", "apples"]]
flight_id = int(flask.request.args.get('id'))
flight_name = flask.request.args.get('flight')
flight_abbreviation = flask.request.args.get('name')
selected = dict(d)[flight_abbreviation]
return flask.jsonify({"result":f'<p>Thank you for choosing {flight_name}</p>'})

关于python - 如何在 Flask 中按下按钮时获取 HTML <tr> 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52646107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com