我有一个烧瓶应用程序,并希望定期更新模板中的值。该值将来自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
中返回的值?
答案 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>