使用JQuery/AJAX调用函数并在Flask模板中使用其值
我有一个flask应用程序,希望定期更新模板中的值。该值将来自烧瓶路径。例如,我的视图定义如下:使用JQuery/AJAX调用函数并在Flask模板中使用其值,jquery,python,flask,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
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中的返回值?我认为,最好从视图中返回结构化响应json/xml 因此,我的第一个建议是关于您的“价格”观点: 观点 使用简化AJAX调用的jquery index.html
现在工作!谢谢
@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})
<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>