gpt4 book ai didi

javascript - 我想使用 GIN 将 JSON 数据带到 Golang 制作的服务器

转载 作者:IT王子 更新时间:2023-10-29 02:12:39 26 4
gpt4 key购买 nike

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

这是我的代码:

加入.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("에러가 발생하였습니다. 잠시 후에 다시 시도하여 주세요.");
}
}
})

主.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)
})

最佳答案

提交表单时,服务器期望的内容类型是application/x-www-form-urlencoded。如果使用 inut type="file"上传文件,内容类型应该是 multipart/form-data

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

link to the w3.org spec for forms

关于javascript - 我想使用 GIN 将 JSON 数据带到 Golang 制作的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41736234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com