在 Flask 中按下按钮时如何获取 HTML <tr> 标签?

How to get HTML <tr> tags when pressing button in Flask?

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

我想在用户按下 "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"] returns 错误请求错误。有没有办法获得这样的 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>'})