我想使用GIN将JSON数据传输到由Golang制作的服务器。

huangapple go评论108阅读模式
英文:

I want to bring JSON data to server made by Golang using GIN

问题

我正在使用Golang和GIN制作Web应用程序。当Ajax类型为GET时,我可以传递JSON数据,但是当Ajax类型为POST时,我不知道如何将JSON数据发送到GO服务器。我尝试使用PostForm()GetPostForm()方法,但是没有起作用。请帮助我。

这是我的代码:

join.js

var json_memberInfo = `{ 
    "id": "`+id+`",
    "password": "`+password+`",
    "name": "`+name+`",
    "birthday": "`+birthday+`",
    "tel": "`+tel+`",
    "email": "`+email+`"
}`;

var parse_memberInfo = JSON.parse(json_memberInfo);

alert(json_memberInfo);

$.ajax({
    url: "/join",
    type: "POST",
    data: parse_memberInfo,
    contentType: "application/json",
    success: function(result) {
        if (result) {
            //alert("회원가입이 완료되었습니다!");
        }
        else {
            //alert("에러가 발생하였습니다. 잠시 후에 다시 시도하여 주세요.");
        }
    }
})

main.go

router.POST("/join", func(c *gin.Context) {
    id := c.PostForm("id")
    password := c.PostForm("password")
    name := c.PostForm("name")
    birthday := c.PostForm("birthday")
    tel := c.PostForm("tel")
    email := c.PostForm("email")

    fmt.Println(id + " " + password + " " + name + " " + birthday + " " + tel + " " + email)
})

希望对你有所帮助!

英文:

I am making web application using Golang with GIN. I can bring json data when Ajax type is GET, but When Ajax type is POST, I don't no how to send json data to GO server. I used method PostForm() and GetPostForm(), But It is not working. Plz help me.

Here is my code:

join.js

        var json_memberInfo = `{ 
            "id": "`+id+`",
            "password": "`+password+`",
            "name": "`+name+`",
            "birthday": "`+birthday+`",
            "tel": "`+tel+`",
            "email": "`+email+`"
        }`;
        
        var parse_memberInfo = JSON.parse(json_memberInfo);

        alert(json_memberInfo);

        $.ajax({
            url: "/join",
            type: "POST",
            data: parse_memberInfo,
            contentType: "application/json",
            success: function(result) {
                if (result) {
                    //alert("회원가입이 완료되었습니다!");
                }

                else {
                    //alert("에러가 발생하였습니다. 잠시 후에 다시 시도하여 주세요.");
                }
            }
      })

main.go

	router.POST("/join", func(c *gin.Context) {
		id := c.PostForm("id")
		password := c.PostForm("password")
		name := c.PostForm("name")
		birthday := c.PostForm("birthday")
		tel := c.PostForm("tel")
		email := c.PostForm("email")

		fmt.Println(id + " " + password + " " + name + " " + birthday + " " + tel + " " + email)
	})

答案1

得分: 1

当提交表单时,服务器期望的内容类型是application/x-www-form-urlencoded。如果使用input类型为file来上传文件,则内容类型应为multipart/form-data

将内容类型从application/json更改为application/x-www-form-urlencoded将使服务器/后端能够识别传递的数据为表单数据,从而可以使用c.PostForm来检索字段。

表单的w3.org规范链接

英文:

When submitting a form the content type that the server will expect is application/x-www-form-urlencoded. If the inut type="file" for uploading files is used the content type should be multipart/form-data

Changing the content type from application/json to application/x-www-form-urlencoded will let the server/backend identify the data being passed as form data wich will allow for the retrieval of the fields using c.PostForm.

link to the w3.org spec for forms

答案2

得分: 0

我相信gin.Context.PostForm()函数用于访问application/x-www-form-url-encoded数据。要接受application/json数据,可以使用gin.Context.BindJSON函数绑定请求中的值。这可以处理json或form-url-encoded格式的数据(尽管在下面的示例中,结构体只用于处理json)。以下是一个示例的片段:

type Member struct {
  Id          string     `json:"id"`
  Password    string     `json:"password"`
  Name        string     `json:"name"`
  Birthday    string     `json:"birthday"`
  Tel         string     `json:"tel"`
  Email       string     `json:"email"`
}

// 其他代码

router.POST("/join", func(c *gin.Context) {
  var jsonData Member
  if c.BindJSON(&jsonData) == nil {
    fmt.Println(jsonData.Id + " " + jsonData.Password + " " + jsonData.Name + " " +
      jsonData.Birthday + " " + jsonData.Tel + " " + jsonData.Email)
  } else {
    // 处理错误
  }
})

希望对你有帮助!

英文:

I believe the gin.Context.PostForm() functions are for accessing application/x-www-form-url-encoded data. To accept application/json data one can use the gin.Context.BindJSON function for binding the values in the request. This can handle data in either json or form-url-encoded (although in the example below the struct is only annotated for handling json). A snippet of an example for this is:

type Member struct {
  Id          string     `json:"id"`
  Password    string     `json:"password"`
  Name        string     `json:"name"`
  Birthday    string     `json:"birthday"`
  Tel         string     `json:"tel"`
  Email       string     `json:"email"`
}

// various code

router.POST("/join", func(c *gin.Context) {
  var jsonData Member
  if c.BindJSON(&jsonData) == nil {
    fmt.Println(jsonData.Id + " " + jsonData.Password + " " + jsonData.Name + " " +
      jsonData.Birthday + " " + jsonData.Tel + " " + jsonData.Email)
  } else {
    // handle error
  }
}

huangapple
  • 本文由 发表于 2017年1月19日 15:35:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41736234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定