首页 > 解决方案 > 表单提交后Flask返回页面但不刷新

问题描述

我有一个带有表格的注册页面。提交后,它将从 Flask 调用 register 函数。然后这个函数将返回一个url_for("index"). 从我的终端,它确实返回GET / HTTP/1.1" 200。问题是页面没有重定向。我试过直接进入索引页面,没有任何问题。它也会GET / HTTP/1.1" 200在终端中返回。唯一的问题是在提交表单之后。它甚至达到了print("reached")我所做的但页面仍然没有重定向。

对于表单的 action 属性,我尝试过index, /, url_for("index")url_for("register")但无济于事。代码如下所示。谢谢你。

注册.html

<form
    action="{{ url_for('register') }}"
    method="POST"
    class="u-clearfix u-form-horizontal u-form-spacing-15 u-inner-form"
    style="padding: 15px"
>
    <div class="u-form-group u-form-name">
        <input
            type="text"
            placeholder="Enter Address"
            id="name-558c"
            name="IP"
            class="u-border-1 u-border-grey-30 u-input u-input-rectangle"
            required=""
        />
    </div>
    <div class="u-form-group u-form-submit">
        <a class="u-btn u-btn-submit u-button-style">Submit</a>
        <input
            type="submit"
            value="Submit"
            class="u-form-control-hidden"
        />
    </div>
</form>

应用程序.py

@app.route('/')
def index():
    print("reached")
    return render_template("index.html", participant=participant.getall(), visit=visitList)

@app.route('/register', methods=["POST", "GET"])
def register():
    if request.method == "POST":
        #dosomething
        return redirect(url_for("index"))
    else:
        return render_template("register.html")

标签: pythonhtmlformsflask

解决方案


尝试:

return redirect("/")

代替:

redirect(url_for("index"))

另外,我认为您不一定需要表单“目标”属性。


推荐阅读