读取Json Form数据golang

时间:2018-07-21 10:35:31

标签: go go-iris

我正在使用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框架。

1 个答案:

答案 0 :(得分:1)

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

代替:

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

这样做:

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

并在您的Go文件中,将其绑定到您的对象:

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

祝你好运:)