简体   繁体   English

如何使用 Golang 和 Gin Routing 获取 AJAX 响应

[英]How to get and AJAX response using Golang with Gin Routing

Here is my code of Golang (Notice the registerNewUser in the POST ("/register") handler:这是我的 Golang 代码(注意 POST ("/register") 处理程序中的 registerNewUser:

func main(){

    router := gin.Default()
    router.LoadHTMLFiles("../login.html", "../recoverPassword.html")
    router.Static("/css", "../css")
    router.Static("/img", "../img")
    router.Static("/js", "../js")
    router.GET("/", loadMainPage)
    router.POST("/register", registerNewUser)

    router.Run("localhost:8080")
}
func registerNewUser(c *gin.Context) {
    fmt.Print("Nonas")
    log.Print("Sisas")
}

Now, here is my code of javascript:现在,这是我的 javascript 代码:

$.ajax({
                        url: "/register",
                        method: "POST",
                        data: {firstname:Firstname, lastname:Lastname, username:Username, email:Email, password:Password, country:Country},
                        beforeSend:function(){
                            $("#submit_register_form_btn").attr('disabled', true);
                            $("#submit_register_form_btn").val('Conectando...');
                        },
                        success:function(response) {
                            $('#submit_register_form_btn').removeAttr('disabled');
                            alert(response);
                        }
                    });

I need a way to return a string as response from Golang to the AJAX petition我需要一种方法将字符串作为响应从 Golang 返回到 AJAX 请求

fmt and log print to os.Stdout and os.Stderr respectively. fmtlog分别打印到os.Stdoutos.Stderr You need to respond to the web request.您需要响应网络请求。

Gin passes a *gin.Context to your handler for this purpose. *gin.Context ,Gin 将*gin.Context传递给您的处理程序。

https://pkg.go.dev/github.com/gin-gonic/gin#readme-quick-start shows a very small example of returning data through the context. https://pkg.go.dev/github.com/gin-gonic/gin#readme-quick-start展示了一个通过上下文返回数据的小例子。 There are tons of other great examples inhttps://pkg.go.dev/github.com/gin-gonic/gin#readme-api-examples . https://pkg.go.dev/github.com/gin-gonic/gin#readme-api-examples 中有很多其他很棒的例子。

"Context is the most important part of gin," so read the documentation thoroughly after reviewing a few examples to wrap your head around what usage generally looks like. “上下文是 gin 中最重要的部分”,因此在查看了几个示例之后,请仔细阅读文档,以了解通常的用法。

Once you feel like you have your head wrapped around the quickstart, take a look at gin's Context.String .一旦您觉得自己已经完全了解快速入门,请查看 gin 的Context.String You can substitute that for the c.JSON call in the example.您可以将其替换为示例中的c.JSON调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM