我如何请求使用 JavaScript 接收 python 列表以填充点击时的下拉列表并发回选定的响应?

问题描述 投票:0回答:0

我是 Javascript 的新手,我想显示一个简单的

colour_list
作为下拉菜单并返回选定的颜色响应。

我尝试了以下代码片段,但它说未捕获类型错误:$.fn.get_entity 不是函数

后端:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/get_entity', methods=['GET'])
def get_entity():
    try:         
        colour_list = ['Red', 'Blue', 'Orange', 'Yellow', 'Green']        
        entity_wrap = {"entity_options":colour_list}

    except Exception as e:
        print('Exception caught while getting entity list: ',str(e))
        
    return entity_wrap

def main():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

前端(index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Report Generation</title>
    <script src="../static/scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="../static/scripts/select2.js"></script>
    <script>
        $(document).ready(function(){ 

            $("#entity_selection").select2();
            
            $.fn.get_enitity = function() { 
        
                var sub_entity = null;

                $.ajax({
                    url: '/get_entity',
                    dataType: 'json',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify( { "sub_entity": sub_entity } ),
                    processData: false,
                    success: function( data, textStatus, jQxhr ){

                            $("#entity_selection").empty();

                            for (const x of data['entity_options']) { 

                                var option = $('<option></option>').attr("value", x).text(x);
                                $("#entity_selection").append(option);
                            }

                        },
                    error: function( jqXhr, textStatus, errorThrown ){
                        console.log( errorThrown );
                    }
                });  
            }
    
            $.fn.get_entity(); 

        });
    </script>
</head>
<body>    
    <section class="form">
        <div class="Entity">
            <p class="Text"> Entity: </p> 
            <SELECT id="entity_selection"></SELECT><br/>           
        </div>
        <div class="Submit">    
            <button id="submit_button">SUBMIT</button><br/>  
        </div>        
    </section>
</body>
</html>

我想要这样的东西:

javascript python flask web-applications dropdown
© www.soinside.com 2019 - 2024. All rights reserved.