使用JQuery / AJAX调用函数并在Flask模板中使用它的值

时间:2017-07-23 08:34:45

标签: jquery python flask

我有一个烧瓶应用程序,并希望定期更新模板中的值。该值将来自Flask路线。例如,我的观点定义如下:

from . import main
from flask import render_template


@main.route('/')
def index():
    return render_template('index.html')


@main.route('/price')
def price():
    return 5

现在我的index.html:

<html>
<body>

<p id="p1">Replace this text</p>

<script>
  setInterval(function(){
    document.getElementById("p1").innerHTML = "some value";
  }, 5000);
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

如何从js中调用/price路由,然后使用id=p1中返回的值?

1 个答案:

答案 0 :(得分:2)

我认为,最好从视图中返回结构化响应(json / xml)。

所以,我的第一个建议是关于你的'price'观点:

<强>视图

@app.route('/price')
def price():
    # obtain jsonify from Flask: from flask import jsonify
    # you may change the output/format as you need
    return jsonify({'value': 5})

使用jquery(简化AJAX调用),

<强>的index.html

<html>
<body>

<p id="p1">Replace this text</p>

<script>
  setInterval(function(){
    $.get('/price',function(data) {
        // here, we have the data object returned by 'price' endpoint
        // you can access its attributes as a regular JSON object
        document.getElementById("p1").innerHTML = data.value;
    });
  }, 5000);
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>