【问题标题】:Python / Flask / Ajax : send a dict key from client to serverPython / Flask / Ajax:从客户端向服务器发送字典键
【发布时间】:2018-10-14 18:52:43
【问题描述】:

我试图找出在我的页面上单击了哪个图像(使用 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>

顺便说一句,包含效果很好。

非常感谢您的帮助

【问题讨论】:

    标签: python ajax post flask


    【解决方案1】:

    如果您使用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>
    

    对于

    【讨论】:

    • 嗨,Pranav,感谢您的快速回复,但是当点击事件发生在这个特殊的 img?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多