如何在Flask中获取表单提交的用户输入并展示到网页上
原因说明
你提交表单后URL带参数是因为HTML的<form>标签没有指定method和action属性,默认会以GET方式把表单数据拼接到当前页面的URL后作为查询参数,所以你输入的54会出现在estimate参数里。
解决方案
第一步:修改Flask代码
你需要导入Flask的request对象来获取URL里的查询参数,再把参数传递给模板渲染:
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): # 获取查询参数里的estimate值,没有的话默认是空字符串 estimate_val = request.args.get('estimate', '') # 把值传给模板,对应模板里的estimate变量 return render_template('index.html', estimate=estimate_val) @app.route('/my-link/') def my_link(): temp = 0 for i in range(10): temp = i return str(temp) if __name__ == '__main__': app.run(debug=True, port=8000)
第二步:修改HTML模板
在页面合适的位置展示拿到的estimate值即可:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <div> <h1>Home Page</h1> <!-- 如果有输入的面积值就展示 --> {% if estimate %} <p>你输入的面积是:{{ estimate }} 平方英尺</p> {% endif %} </div> <form> <label for="estimate">Enter Sq. ft.</label><br> <input type="text" id="estimate" name="estimate" value="Ex. 1000"><br> <input type="submit" value="Calculate Estimate"> </form> <a href="/my-link/">Click me</a> </body> </html>
修改完重启服务后,输入数值点击提交按钮,页面就会直接显示你输入的内容。
内容的提问来源于stack exchange,提问作者Soccerball123
相关产品推荐
相关产品推荐

