繁体   English   中英

Python / Flask / Ajax:从客户端向服务器发送字典密钥

[英]Python / Flask / Ajax : send a dict key from client to server

我试图找出页面上单击了哪个图像(使用Flask生成),然后将此图像的ID发送给使用Ajax的python程序。 这些图像通过循环显示,如下所示:

_result_remote.html:

{% for key, value in resultat.vars_buttons.items() %}
    <div class="tuile{{1+loop.index%23}} news col-xs-4 col-lg-2">
        <img id ="{{key}}"style="margin-top:-5px;" src="../static/img/remote/tvb.png" width="30" >{{ value }}
    </div>
{% endfor %}

我试着将此脚本放在{%endfor%}语句之前:

$(function() {
    $('img#{{key}}').on("click", function (e) {
        var id = $(this).attr("id");
    $.ajax({
        url: "/remote",
        type: "POST",
        id: id})
    });
});

最后在我的app.py中:

app.py:

@app.route('/remote', methods=['POST'])
def remote():
    commande =  request['id'];
    return print(commande)

其他信息:我的页面名为_result_remote.html,因为它实际上是另一个页面中的包含,其呈现方式如下:

app.py:

@app.route('/')
def accueil():
    resultat = {'module_identique' : "", "module":"", "vars": {}}
    return render_template("accueil_modulable.html", titre="Bienvenue!",resultat=resultat)

accueil_modulable.html:

<div class="row result {{ resultat.module_identique }}" id="ajax_result">
    {% for module in modules %}
        {% if resultat.module == module %}
            {% include '_result_'+ module +'.html' %}
        {% endif %}
    {% endfor %}
</div>

包括顺便说一句。

非常感谢您的帮助

如果您使用的是Jinja 2.9或更高版本,则可以使用with关键字传递上下文变量。

<div class="row result {{ resultat.module_identique }}" id="ajax_result">
    {% for module in modules %}
        {% if resultat.module == module %}
            {% with resultat=resultat %}
                {% include '_result_'+ module +'.html'%}
            {% endwith %}
        {% endif %}
    {% endfor %}
</div>

对于<2.9版的Jinja版本,您必须添加扩展名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM