提交 Flask 表单而不重新渲染页面
我正在用 Flask 构建一个表单,下面是我的 Flask 服务器的简化版本
app = Flask(__name__)
@app.route("/", methods = ["POST", "GET"])
def main_page():
if request.method == "POST":
# some cool stuff
return render_template("main.html")
if __name__ == "__main__":
app.debug = True
app.run()
问题是,当用户提交表单时,它会重新渲染页面,跳转到页面顶部。这使得用户体验有点糟糕。 如何在不重新渲染整个页面的情况下获取表单的数据?
I'm building a form with flask, below is the simplified version of my flask server
app = Flask(__name__)
@app.route("/", methods = ["POST", "GET"])
def main_page():
if request.method == "POST":
# some cool stuff
return render_template("main.html")
if __name__ == "__main__":
app.debug = True
app.run()
The problem is that it re-renders the page when the user submits the form, jumping to the top of the page. That makes the user experience kinda bad.
How to get the data of the form without re-rendering the entire page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想提交表单数据,但不想完全重新渲染页面,您唯一的选择是使用 AJAX。
在以下示例中,使用 Fetch API 发送表单数据。服务器上的处理本质上保持不变,因为表单数据以相同的格式提交。
但是,由于这里通常有 JSON 格式的响应,因此我建议外包端点,以便将 HTML 和 JSON 路由分开。
If you want to submit the form data, but don't want to completely re-render the page, your only option is to use AJAX.
In the following example, the form data is sent using the Fetch API. The processing on the server remains essentially the same because the form data is submitted in the same format.
However, since there is usually a response in JSON format here, I advise outsourcing the endpoint, so that there is a separation between HTML and JSON routes.