duanji1902
2018-07-21 10:35
浏览 196
已采纳

读取Json Form数据golang

I am sending form data in JSON & serialize format to golang server using ajax. I am not able to read those data.

I am using kataras/iris golang framework.

Below is my code -

(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\"}"

And I am trying to fetch the data from server using below code -

// 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))

My all data is blank, How to grab the data? I am using https://github.com/kataras/iris golang framework.

</div>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushang7209 2018-07-21 11:19
    已采纳

    One the one hand, you are sending a JSON to the server, but when fetching the parameters you are fetching them as "application/x-www-form-urlencoded", first, send the JSON parameters as JSON and not as string, remove the stringifying, i.e:

    instead of:

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

    do:

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

    and in your Go file, bind it to your object:

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

    good luck :)

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题