[英]Flask template won't re-render
一旦事件被触发,我试图重新渲染烧瓶模板(index.html)。 这是我正在尝试做的简化版本:最初呈现页面并且控制台显示一些文本(“初始数据”)。 然后用户单击一个按钮,页面会重新呈现一些新数据(“新数据”)。 在真实版本中,python 代码对数据进行了一些繁重的处理,因此使用纯 HTML/JS 无法做到这一点,我确实需要重新渲染页面。
这是当前的设置:
主文件
from flask import Flask, request, render_template, redirect, Response, url_for
app = Flask(__name__)
@app.route('/', methods = ['GET'])
def index():
return render_template(("index.html"), val="Initial Data")
@app.route('/newData', methods = ['GET', 'POST'])
def newData():
return redirect(url_for("index", val="New Data"))
if __name__ == '__main__':
app.run()
模板/index.html
<script src='https://code.jquery.com/jquery-3.3.1.min.js'></script>
<body>
<button onclick='sendData()'>send data</button>
</body>
<script>
window.onload = function () { console.log({{val}}) };
function sendData() {
var str = 'This is some data';
$.ajax({
url: '/newData',
type: 'POST',
data: str,
success: function () { console.log('success') },
error: function (error) { console.log(error) }
})
}
</script>
目前发生的事情是当页面最初呈现时(如预期)“初始数据”出现在控制台中,按钮单击调用该函数,然后模板没有任何反应。 我希望“新数据”接下来出现在控制台中,显示模板已被重新渲染,但这并没有发生。 我知道 python 函数 newData 正在被调用,但 index.html 没有用新参数重新呈现。 我已经尝试了该行的各种选项,例如return render_template("index.html", val="New Data")
和return redirect("index.html", val="New Data")
,但没有任何重新- 使用新数据渲染模板。
谢谢。
您不能以这种方式使用重定向。 当您使用重定向时,它将重定向到烧瓶视图,然后将运行该视图中的所有代码,包括return render_template("index.html", val="Initial Data")
您可以尝试使用 get 参数:
@app.route('/<val>', methods = ['GET'])
def index(val):
return render_template(("index.html"), val=val)
@app.route('/newData/<val>', methods = ['GET', 'POST'])
def newData(val):
return redirect(url_for("index", val=val))
或者,如果您愿意,可以通过执行以下操作,使用现有的 ajax 代码完成此任务:
from flask import request
@app.route('/newData', methods = ['GET', 'POST'])
def newData():
return request.data # this will access the data you sent using ajax
# and return it back in the response
在您的 js 代码中:
window.onload = function () { console.log({{val}}) };
function sendData() {
var str = 'This is some data';
$.ajax({
url: '/newData',
type: 'POST',
data: str,
success: function (res) { console.log(res) },
// res is the response from the server
// (from return request.data)
error: function (error) { console.log(error) }
})
}
正如@shifloni 指出的那样,你不能这样做。 如果可以的话,AJAX 调用只会将 http render_template 作为变量返回到 Javascript 中,因此它不会刷新您的浏览器。 我能看到的这个最简单的方法是重组为:
@app.route('/', methods=['GET'], defaults={'val': 'Initial Data'})
@app.route('/<val>', methods=['GET'])
def index(val):
return render_template(("index.html"), val=val)
并在您的 HTML 中这样做:
<body>
<button onclick='sendData()'>send data</button>
</body>
<script>
var sendData = function() {
var strData = 'This is some data';
urlGet = {{ url_for('app.index') }} + '/' + strData
location.href = urlGet;
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.