【问题标题】:Flask redirect after ajax request successajax请求成功后烧瓶重定向
【发布时间】:2026-02-08 00:35:02
【问题描述】:

我开发了一个地图应用,前端是用 Flask 创建的。使用 ajax 请求搜索外部后端(使用 django 框架创建)时。我想 在从 ajax 响应返回后重定向 url(如果成功与否)。但是,我不知道最好的方法!

submitHandler: function () {
        /********* GET USER TOKEN WITH AJAX REQUEST**********/
        $.ajax({
            method: 'POST',
            url: "url for get token",
            data: {
                username: $('#email-log').val(),
                password: $('#password-log').val()

            },
            success: function (response) {
                if(response.d == true) {
                    localStorage["username"] = $('#username-log').val();
                    localStorage["user_token"] = response['token'];
                    window.location = "{{url_for('maps')}}";
                }
            },
        });
    },

我在哪里做这个重定向? 在 ajax 请求 中,在 form action = "" 中,在某处使用 url_for()

我迷失在所有这些方法中

【问题讨论】:

  • 你不能在 javacript 中使用 url_for。你也需要发送变量吗?还是只是重定向?

标签: redirect flask


【解决方案1】:

如果您只想在 Ajax 成功后重定向,您可以这样做:

$.ajax({
        // do what you want,
        success: function(){
           window.location.href = "/url/for/route/"     //redirect url
           // or
           window.location.replace("url/for/route")
        }
    });

【讨论】:

  • 我尝试过,但不起作用:window.location.href = "127.0.0.1:5000/maps"; window.location.replace("127.0.0.1:5000/maps");
  • 改成这样:window.location.href = "/maps";成功了吗?
  • 此登录表单在引导模式窗口中,可能是此失败的原因?
  • 你真的必须使用ajax吗?为什么不使用简单的登录表单。