Flask动态依赖下拉菜单列表

7

我开始学习一些Flask应用程序编程,一直在尝试让下拉菜单正常工作,但是迄今为止我没有成功。我想要做的是,当用户从第一个下拉列表中选择一种食品类型时,它应该从数据库中获取相应的列表并填充第二个下拉列表。我不知道如何在进行选择后快速发送请求。我真的不明白这里应该做什么。

<body>
  <div>
    <form action="{{ url_for('test') }}" method="POST">
      <div>
        <label>Food:</label>
        <select id="food" name="food" width="600px">
        <option SELECTED value='0'>Choose your fav food</option>  
        {% for x in food %}
          <option value= '{{ x }}'>{{x}}</option>
        {% endfor %}
      </select>
        <!-- After a selection is made, i want it to go back to the database and fectch the results for the below drop box based on above selection -->
      </div>
      <div>
        <label>Choose Kind of Food:</label>
        <select id="foodChoice" name="foodChoice" width="600px">
        <option selected value='0'>Choose a kind</option>
        {% for x in foodChoice %}
          <option value= '{{ x }}'>{{x}}</option>
        {% endfor %}
      </select>
      </div>
      <div>
        <input type="submit">
      </div>
    </form>
  </div>

app.html

@app.route('/', method = ['GET', 'POST'])
def index():
    foodList = [ i.type for i in db.session.query(FoodType)]
    return render_template('main.html', food=foodList)

@app.route(/foodkind', method = ['GET', 'POST'])
def foodkind():
        selection = request.form['foodChoice']
        foodKind = [ i.kind for i in db.session.query(FoodType).filter(FoodKind == selection)]
        return render_template('main.html', foodChoice = foodKind)

我看了很多问题,但还没有找到任何简单的帮助我解决问题的东西。如果有人能为我演示一下代码,那就太好了,这样我可以从中学习。

1个回答

8
您需要在这里使用Ajax检索与您选择的食品种类有关的食品列表。因此,在您的模板中,您需要包含类似于以下内容的内容:
<html>
  <head>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous">
    </script>

    <script>
      $(document).ready(function() {
        $('#foodkind').change(function() {

          var foodkind = $('#foodkind').val();

          // Make Ajax Request and expect JSON-encoded data
          $.getJSON(
            '/get_food' + '/' + foodkind,
            function(data) {

              // Remove old options
              $('#food').find('option').remove();                                

              // Add new items
              $.each(data, function(key, val) {
                var option_item = '<option value="' + val + '">' + val + '</option>'
                $('#food').append(option_item);
              });
            }
          );
        });
      });
    </script>
  </head>

  <body>
    <form>
      {{ form.foodkind() }}
      {{ form.food() }}
    </form>
  </body>
</html>

这段代码会制作一个缩写的Ajax请求,用于获取JSON编码的数据。这些数据包含了食品选择框的值列表。
为了使其工作,您需要在Flask视图中添加一个端点/get_food/<foodkind>
food = {
    'fruit': ['apple', 'banana', 'cherry'],
    'vegetables': ['onion', 'cucumber'],                                                 
    'meat': ['sausage', 'beef'],
}


@app.route('/get_food/<foodkind>')
def get_food(foodkind):
    if foodkind not in food:                                                                 
        return jsonify([])
    else:                                                                                    
        return jsonify(food[foodkind])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接