首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >烧瓶:基于优先选择的下拉值

烧瓶:基于优先选择的下拉值
EN

Stack Overflow用户
提问于 2017-03-19 13:10:35
回答 1查看 6.2K关注 0票数 4

我试图限制在下拉列表中的选择,基于用户所做的优先选择。我的酒瓶是这样的:

init.py

代码语言:javascript
运行
复制
@app.route('/create/', methods=['GET','POST'])
def create():
    mySQL2 = SelectCustomer(session['ID']) #displayed invoicereceiver
    global sessioncur
    try:
        form = CreateinvoiceForm(request.form)
        if request.method == 'POST' and form.validate():
            #HEADER
            #This fetches from HTML
            customer = request.form.get('customer')
            goodsrec = request.form.get('goodsrec')
    return render_template("createinvoice.html", form=form,  mySQL2 = mySQL2)

客户是从html表单中填充的,使用mySQL2作为可从中选择的变量:

html选择表单

代码语言:javascript
运行
复制
<select required name="customer" class="selectpicker form-control" , 
placeholder="Select">
<option selected="selected"></option>
{% for o in mySQL2 %}      
<option value="{{ o[2] }}">{{ o[2] }}</option>  
{% endfor %}
</select>

对goodsrec的选择必须取决于所选择的客户。我的想法是获取客户ID,如下所示:

代码语言:javascript
运行
复制
c, conn = connection()
customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" +
str(customer) +"' limit 1")
customerID = c.fetchone()[0]

然后,我可以在函数中使用这个值,以获得带有该ID的良好接收者:

代码语言:javascript
运行
复制
def SelectGoodsrecSEE(customerID):
    c,conn = connection()
    c.execute("SELECT * FROM goodsrec WHERE Gr_Cm_id=" +str(id))
    mySQL8 = c.fetchall()
    c.close()
    conn.close()
    gc.collect()
    return mySQL8

到目前为止,我很肯定这会奏效。我不知道的是如何构造瓶,使它装载第一个选择,并考虑到它的第二个。类似于html,我必须通过mySQL8循环。但是,在烧瓶里的结构是如何完成的呢?此刻我所拥有的一切

代码语言:javascript
运行
复制
@app.route('/create/', methods=['GET','POST'])
def create():
    mySQL2 = SelectCustomer(session['ID']) #displayed invoicereceiver
    global sessioncur
    try:
    form = CreateinvoiceForm(request.form)
    if request.method == 'POST' and form.validate():
        #HEADER
        #This fetches from HTML
        customer = request.form.get('customer')
        c, conn = connection()
        customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" +
        str(customer) +"' limit 1")
        customerID = c.fetchone()[0]
        mySQL8 = SelectGoodsrecSEE(customerID)
        goodsrec = request.form.get('goodsrec')
    return render_template("create.html", form=form,  mySQL2 = mySQL2)

我需要能够将mySQL8传递给create.html,这样我就可以在html中从中选择内容。有什么想法吗?希望我要找的东西或多或少是清楚的。

编辑

SELECT * FROM goodsrec WHERE Gr_Cm_id=18; mySQL8

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-20 13:02:58

SQL注入风险

首先,也是最重要的是,您应该改进代码,因为您现在使用了它,您很容易受到SQL注入攻击。因此,是这样的,而不是:

代码语言:javascript
运行
复制
c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" + str(customer) + "' limit 1")

建议的用法是:

代码语言:javascript
运行
复制
sql = 'SELECT Cm_Id FROM customer WHERE Cm_name = %s LIMIT 1'
parameters = [str(customer)]
c.execute(sql, parameters)

另外还有几个讨论这个问题的帖子:

实现级联选择

Python:

代码语言:javascript
运行
复制
@app.route('/create/', methods=['GET','POST'])
def create():
    mySQL2 = SelectCustomer(session['ID'])
    global sessioncur
    try:
        form = CreateinvoiceForm(request.form)
        if request.method == 'POST' and form.validate():
            customer = request.form.get('customer')
            goodsrec = request.form.get('goodsrec')
            # do stuff with submitted form...
    return render_template("createinvoice.html", form=form,  mySQL2 = mySQL2)


@app.route('/get_goods_receivers/')
def get_goods_receivers():
    customer = request.args.get('customer')
    print(customer)
    if customer:
        c = connection()
        customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name = %s LIMIT 1", [customer])
        customerID = c.fetchone()[0]
        print customerID
        c.execute("SELECT * FROM goodsrec WHERE Gr_Cm_id = %s", [customerID])
        mySQL8 = c.fetchall()
        c.close()
        # x[0] here is Gr_id (for application use)
        # x[3] here is the Gr_name field (for user display)
        data = [{"id": x[0], "name": x[3]} for x in mySQL8]
        print(data)
    return jsonify(data)

HTML/Javascript:

代码语言:javascript
运行
复制
<select name="customer" id="select_customer" class="selectpicker form-control">
    <option selected="selected"></option>
    {% for o in mySQL2 %}
    <option value="{{ o[2] }}">{{ o[2] }}</option>
    {% endfor %}
</select>

<select name="goodsrec" id="select_goodsrec" class="selectpicker form-control" disabled>
    <option>Select a Customer...</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script charset="utf-8" type="text/javascript">
    $(function() {
        var dropdown = {
            customer: $('#select_customer'),
            goodsrec: $('#select_goodsrec')
        };

        // function to call XHR and update goodsrec dropdown
        function updateGoodsrec() {
            var customer = dropdown.customer.val();
            dropdown.goodsrec.attr('disabled', 'disabled');
            console.log(customer);

            if (customer.length) {
                dropdown.goodsrec.empty();
                $.getJSON("{{ url_for('get_goods_receivers') }}", {customer: customer}, function(data) {
                    console.log(data);
                    data.forEach(function(item) {
                        dropdown.goodsrec.append(
                            $('<option>', {
                                value: item.id,
                                text: item.name
                            })
                        );
                    });
                    dropdown.goodsrec.removeAttr('disabled');
                });
            }
        }

        // event listener to customer dropdown change
        dropdown.customer.on('change', function() {
            updateGoodsrec();
        });

    });
</script>
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42886965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档