首页 > 解决方案 > Ajax 帖子未重定向后重定向

问题描述

是的,我知道这与其他问题相似,但是 Brython 语法和功能有很大不同,以至于它们的解决方案在这里不适用。

在使用 Ajax 成功发布后,网页不会重定向到 Flask 告诉它的内容。第一个代码片段中的 print 语句执行并打印来自 HTML 的值,Flask 调试告诉我有一个成功的 get 请求(重定向),但网页没有重定向。这是我的代码:

@app.route("/test", methods=["POST", "GET"])
def testing():
    if request.method == "POST":
        print(request.values["test"])
        return redirect(url_for("success"))
    else:
        return render_template("test.html")

和 HTML:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Testing</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython_stdlib.js"></script>
    <body onload="brython()">
        <script type="text/python">
            from browser import ajax
            ajax.post(url="{{ url_for('testing') }}", data={"test": "this is a test"})
        </script>
    </body>
</html>

这是来自控制台的调试:

127.0.0.1 - - [14/May/2021 18:31:08] "GET /test HTTP/1.1" 200 -
this is a test
127.0.0.1 - - [14/May/2021 18:31:10] "POST /test HTTP/1.1" 302 -
127.0.0.1 - - [14/May/2021 18:31:10] "GET /success HTTP/1.1" 200 -

我应该怎么做才能使它成功重定向?

标签: pythonajaxflaskbrython

解决方案


当您运行 ajax.post 时,您将在 javascript 中发出异步调用。您正在寻找的是回调。来自brython 文档的评论

from browser import document, window, ajax

def on_complete(req):
   if req.status == 200 or req.status == 0:
       # document["result"].html = req.text  # Commented out example code.
       window.location.href="{{ url_for('success') }}"
   else:
       document["result"].html = "error " + req.text

req = ajax.Ajax()
req.bind('complete', on_complete)

推荐阅读