【问题标题】:Flask Dynamic dependent dropdown listFlask 动态依赖下拉列表
【发布时间】:2017-11-22 15:15:25
【问题描述】:

我开始阅读一些烧瓶应用程序编程,我一直试图让下拉菜单工作,但到目前为止我没有运气。我想要做的是,当用户从第一个下拉列表中选择一种食物类型时,它应该从数据库中获取相应的列表并填充第二组下拉列表。一旦做出选择,我不知道如何让它发送一个快速请求。我真的不明白这里应该做什么。

<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)

我查看了很多问题,但还没有找到任何简单的可以帮助我的问题。如果有人可以为我演示一段代码,那将是非常棒的,这样我就可以查看并从中学习。

【问题讨论】:

    标签: javascript jquery python html flask


    【解决方案1】:

    您需要在此处使用 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>
    

    此代码将对 JSON 编码的数据进行速记 Ajax 请求。此数据包含您的食物选择框的值列表。

    为此,您需要将端点 /get_food/&lt;foodkind&gt; 添加到您的 Flask 视图中:

    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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2018-06-25
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多