首页 > 解决方案 > Flask:jQuery 中的 Jinja

问题描述

我正在通过烧瓶制作一个网络应用程序,并且我正在使用 jQuery 以便在线程完成后呈现不同的模板。模板的路径是可变的,我想用 jinja 在我的 jQuery (Ajax) 脚本中指定它。我现在正在使用以下代码,这会导致以下错误:

HTML:

{% block script %}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        var refresh_id = setInterval(function () {
            $.get(
                "{{ url_for('thread_status', jobid={{ jobid }}) }}",
                function (data) {
                    console.log(data);
                    if (data.status == 'finished') {
                        if (data.success == 'success'){
                            window.location.replace("{{ url_for('result' , jobid={{ jobid }}) }}");
                        }
                        else if (data.succes == "failed"){
                            window.location.replace("{{ url_for('typing_failed') }}");
                        }
                        
                    }
                }
            )
        }
            , 5000); // refresh every 5 seconds
    });
</script>
{% endblock %}

Python:

@app.route('/<jobid>/results/')
def result(jobid):
    return render_template("results.html")

@app.route('/<jobid>/status')
def thread_status(jobid):
    global th
    return jsonify(dict(status=('running' if th.is_alive() else 'finished'), success=success))

错误:

line 8, in template
    "{{ url_for('thread_status', jobid={{ jobid }}) }}",
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

标签: pythonjqueryajaxflaskjinja2

解决方案


{{ }}调用时无需重用符号,url_for()因为它是将表达式打印到模板输出的简写。

正确的用法是{{ url_for('thread_status', jobid=jobid) }}.


推荐阅读