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

时间:2018-10-04 11:57:21

标签: python forms flask tr

我的HTML模板的格式在浏览器中如下所示:

enter image description here

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

这是我的表单的样子:

<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标签值?

1 个答案:

答案 0 :(得分:2)

您可以为将要显示的每个项目创建唯一的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>'})