为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
动漫人物 2023-07-26 19:55:06
我们正在尝试将 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)        }    }
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

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



查看完整回答
反对 回复 2023-07-26
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信