Flask Dynamic dependent dropdown list

前端 未结 1 559
日久生厌
日久生厌 2021-02-02 03:44

I started reading into some flask application programming and I have been trying to get drop down menu to work, but so far I have had no luck. What I want to do is, when the use

相关标签:
1条回答
  • 2021-02-02 04:35

    You need to use Ajax here to retrieve a list of the food depending on your choice of foodkind. So in your template you will need to include something like this:

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

    This code will make a shorthand Ajax request for JSON-encoded data. This data contains a list of the values for your food select box.

    For this to work you will need to add an endpoint /get_food/<foodkind> to your Flask views:

    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])
    
    0 讨论(0)
提交回复
热议问题