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

读取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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Ros2 moveit2 Windows环境配置,有偿,价格可商议。
  • ¥15 有关“完美的代价”问题的代码漏洞
  • ¥15 请帮我看一下这个简易化学配平器的逻辑有什么问题吗?
  • ¥15 暴力法无法解出,可能要使用dp和数学知识
  • ¥15 wpf通过绑定控件自身的值,来实现背景颜色的切换
  • ¥15 CDH6.3 运行hive -e hive -e "show databases;"报错:hive-env.sh:行24: hbase-common.jar: 权限不够
  • ¥15 SSRS制作的报表打开报错,无法正常显示网页
  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 javaweb项目无法正常跳转