如何使用 go 和 javascript 在 json post 后重定向浏览器?

我们正在尝试将 JSON 格式的 HTML 表单发送到 GO 代码。我们已经实现了这一点,但是,现在我们很困惑,因为我们无法使浏览器重定向到相应的网页。重定向指令直接在 Insomnia 上发送 json 可以正常工作(它返回成功状态并显示新页面),但在浏览器中则不行。也许我们遗漏了一些代码,但我们无法找到我们遗漏了什么。请帮忙。


发送json的javascript代码:


  jQuery(document).on('submit', '#login', function(event){

        event.preventDefault();


        jQuery.ajax({

            url: '/login/',

            type: 'POST',

            dataType: 'json',

            data: JSON.stringify($(this).serializeFormJSON())

        })

        .done(function(response){

            location.href = 'response';

        })

        .fail(function(resp){

            console.log("resp");

        })

        .always(function(){

            console.log("complete");

        })

    });

验证此表单的 Go 代码:


    func POSTLoginHandler(w http.ResponseWriter, r *http.Request) {

        var user users.User

        err := json.NewDecoder(r.Body).Decode(&user)

        if err != nil {

            w.WriteHeader(http.StatusBadRequest)

        } else {

            validCredentials, err := users.ValidarCredenciales(user)

            if err != nil {

                w.WriteHeader(http.StatusInternalServerError)

            } else if validCredentials {

                err = cookies.GenerarCookie(w, r, user.Email)

                if err != nil {

                    w.WriteHeader(http.StatusInternalServerError)

                } else {

                    http.Redirect(w, r, "/dashboard/", http.StatusSeeOther)

                }

            } else {

                http.Redirect(w, r, "/forbidden/", http.StatusSeeOther)

            }

        }

    }



    func GetDashboardUser(w http.ResponseWriter, r *http.Request) {

        exists, err := cookies.VerifyCookie(r)

        if err != nil {

            w.WriteHeader(http.StatusInternalServerError)

        } else if exists {

            http.ServeFile(w, r, "static/template.html")

        } else {

            http.Redirect(w, r, "/", http.StatusSeeOther)

        }

    }


动漫人物
浏览 109回答 1
1回答

慕哥6287543

当您发出 AJAX 请求时,这都是 JavaScript,而不是用户看到的页面。因此,当您的 AJAX 请求获得重定向响应时,AJAX 请求就会被重定向。仅当用户导航到的 URL 返回重定向时,用户看到的页面才会重定向。如果你想要 JavaScript 改变浏览器页面,你必须编写 JS 来做到这一点,它不会自动发生。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go