-1

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

我正在使用kataras/irisgolang 框架。

下面是我的代码 -

(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 框架。

4

1 回答 1

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) 

祝你好运 :)

于 2018-07-21T11:19:15.343 回答