【发布时间】:2020-03-29 17:58:04
【问题描述】:
Flask 没有使用新变量重新渲染模板页面。
Flask 代码 (app.py):
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route("/",methods = ['GET', 'POST'])
@app.route("/<value>",methods = ['GET', 'POST'])
def index(value=1):
print(value)
return render_template('home.html',number=value)
@app.route("/next",methods = ['GET', 'POST'])
def next():
if request.method == 'POST':
last_num = list(dict(request.form).keys())[0]
last_num = int(last_num)
return redirect(url_for("index",value=last_num+1))
if __name__ == '__main__':
app.run()
HTML 页面 (home.html):
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('#submit').click(function() {
$.ajax({
url: '/next',
data: String(Number(document.getElementById("number").textContent)),
type: 'POST',
success: function(response) {
console.log("Awesome");
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<div id="number">
{{number}}
</div>
<button type="button" id="submit">Next</button>
</body>
</html>
HTML 页面中的(最后一个)数字很好地到达了烧瓶代码,index 函数也获得了递增的值。但是 HTML 页面不会使用新的 number 变量重新加载。
【问题讨论】:
-
(1) 为什么你在 HTML 中禁用了
onClick而在 JS 中却应用了相同的功能? (2) 从 Ajax 调用重定向到页面并不简单(因为浏览器不期望它)。看看这个答案:stackoverflow.com/questions/199099/… -
@RahulBharadwaj 有没有更简洁的方式从 HTML 到 Flask(而不是 ajax)进行通信并使用数据从 Flask 重新呈现 HTML 页面?
标签: javascript python jquery html flask