【问题标题】:Redirect after Ajax post not redirectingAjax 帖子未重定向后重定向
【发布时间】:2021-05-14 23:45:39
【问题描述】:

是的,我知道这与其他问题类似,但 Brython 语法和函数有很大不同,因此它们的解决方案不适用于此处。

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

@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 -

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

【问题讨论】:

    标签: python ajax flask brython


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 哦,这更有意义。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多