gpt4 book ai didi

go - 读取Json Form数据golang

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:52 26 4
gpt4 key购买 nike

我正在使用 ajax 将 JSON 和序列化格式的表单数据发送到 golang 服务器。我无法读取这些数据。

我正在使用 kataras/iris golang 框架。

下面是我的代码-

(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);

var Contact = {
sendMessage: function() {
return m.request({
method: "POST",
url: "/send/message",
data: JSON.stringify(jQuery('#contact-form').serializeFormJSON()),
withCredentials: true,
headers: {
'X-CSRF-Token': 'token_here'
}
})
}
}
<!-- Data looks like below, what is sent -->
"{\"first_name\":\"SDSDFSJ\",\"csrf.Token\":\"FjtWs7UFqC4mPlZU\",\"last_name\":\"KJDHKFSDJFH\",\"email\":\"DJFHKSDJFH@KJHFSF.COM\"}"

我正在尝试使用以下代码从服务器获取数据 -

// Contact form
type Contact struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}

contact := Contact{}
contact.FirstName = ctx.FormValue("first_name")
contact.LastName = ctx.FormValue("last_name")
contact.Email = ctx.FormValue("email")
ctx.Writef("%v", ctx.ReadForm(contact))

我的所有数据都是空白,如何抓取数据?我正在使用 https://github.com/kataras/iris golang 框架。

最佳答案

一方面,您正在向服务器发送 JSON,但是在获取参数时,您将它们作为“application/x-www-form-urlencoded”获取,首先,将 JSON 参数作为 JSON 而不是作为字符串,删除字符串化,即:

代替:

JSON.stringify(jQuery('#contact-form').serializeFormJSON())

做:

jQuery('#contact-form').serializeFormJSON()

然后在您的 Go 文件中,将其绑定(bind)到您的对象:

var contact []Contact 
err := ctx.ReadJSON(&contact)

祝你好运:)

关于go - 读取Json Form数据golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455209/

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