我是 Flask 的新手,我一直在尝试在两个网页之间传递一个变量。第一个是一个简单的表单来接受一个数字,第二个页面只显示输入的内容。
表单页面的 HTML:
<!doctype html>
<html>
<body>
<form action ="{{ url_for('return_form', glon="glon") }}" method="post">
Galactic Longitude: <input type="text" name="glon">
<button type="submit">Submit</button>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
显示页面的 HTML:
<!doctype html>
<body>
<p> {{ glon }} </p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Flask 脚本目前看起来像这样:
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/form/', methods = ['GET', 'POST'])
def form():
if request.method == 'POST':
glon = request.form['glon']
#glat = request.form['glat']
return redirect(url_for('return_form', glon=glon))
return render_template('form.html')
@app.route('/return_form/<glon>', methods = ['GET', 'POST'])
def return_form(glon):
return render_template('return_form.html', glon=glon)
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
目前,第二页只显示“glon”而不是传递给表单的数字。
我只是想让变量显示在第二页上,并最终在 return_form 函数中使用它。
所以我没有得到你的方法。下面是我所做的,我稍微改变了代码。希望这能解决您的问题。
主文件
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/form', methods = ['GET', 'POST'])
def form():
if request.method == 'POST':
glon = request.form['glon']
return render_template('display.html', glon=glon)
# @app.route('/return_form/<glon>', methods = ['GET', 'POST'])
# def return_form(glon):
# return render_template('return_form.html', glon=glon)
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
索引.html
<html>
<body>
<form action ="{{ url_for('form') }}" method="post">
Galactic Longitude: <input type="text" name="glon">
<button type="submit">Submit</button>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
显示.html
<!doctype html>
<body>
<p> {{ glon }} </p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)