Flask Dynamic dependent dropdown list

前端 未结 1 563
日久生厌
日久生厌 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:

    
      
    
        
    
        
      
    
      
        
    {{ form.foodkind() }} {{ form.food() }}

    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/ to your Flask views:

    food = {
        'fruit': ['apple', 'banana', 'cherry'],
        'vegetables': ['onion', 'cucumber'],                                                 
        'meat': ['sausage', 'beef'],
    }
    
    
    @app.route('/get_food/')
    def get_food(foodkind):
        if foodkind not in food:                                                                 
            return jsonify([])
        else:                                                                                    
            return jsonify(food[foodkind])
    

    0 讨论(0)
提交回复
热议问题