提交 Flask 表单而不重新渲染页面

发布于 2025-01-10 08:23:52 字数 393 浏览 0 评论 0原文

我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把时间冻结 2025-01-17 08:23:52

如果您想提交表单数据,但不想完全重新渲染页面,您唯一的选择是使用 AJAX
在以下示例中,使用 Fetch API 发送表单数据。服务器上的处理本质上保持不变,因为表单数据以相同的格式提交。
但是,由于这里通常有 JSON 格式的响应,因此我建议外包端点,以便将 HTML 和 JSON 路由分开。

from flask import (
    Flask,
    jsonify,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    # Same cool stuff here.
    print(request.form.get('data'))

    return jsonify(message='success')
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <form name="my-form" method="post">
      <input type="text" name="data" />
      <input type="submit" />
    </form>

    <script type="text/javascript">
      (uri => {
        // Register a listener for submit events.
        const form = document.querySelector('form[name="my-form"]');
        form.addEventListener('submit', evt => {
          // Suppress the default behavior of the form.
          evt.preventDefault();
          // Submit the form data.
          fetch(uri, {
            method: 'post',
            body: new FormData(evt.target)
          }).then(resp => resp.json())
            .then(data => {
              console.log(data);
              // Handle response here.
            });
          // Reset the form.
          evt.target.reset();
        });
      })({{ url_for('upload') | tojson }});
    </script>

  </body>
</html>

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.

from flask import (
    Flask,
    jsonify,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    # Same cool stuff here.
    print(request.form.get('data'))

    return jsonify(message='success')
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <form name="my-form" method="post">
      <input type="text" name="data" />
      <input type="submit" />
    </form>

    <script type="text/javascript">
      (uri => {
        // Register a listener for submit events.
        const form = document.querySelector('form[name="my-form"]');
        form.addEventListener('submit', evt => {
          // Suppress the default behavior of the form.
          evt.preventDefault();
          // Submit the form data.
          fetch(uri, {
            method: 'post',
            body: new FormData(evt.target)
          }).then(resp => resp.json())
            .then(data => {
              console.log(data);
              // Handle response here.
            });
          // Reset the form.
          evt.target.reset();
        });
      })({{ url_for('upload') | tojson }});
    </script>

  </body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文