为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以绑定到自定义结构类型的地图对象?

是否可以绑定到自定义结构类型的地图对象?

Go
慕侠2389804 2023-05-08 18:08:51
我的问题是,如何在地图对象(变量)中绑定(自动绑定?)自定义结构类型?这是我的自定义结构类型type Tetris struct {    ... ...    NowBlock           map[string]int     `form:"nowBlock" json:"nowBlock"`    ... ...}这是我的ajax代码 $.ajax({     type : "POST"     , url : "/game/tetris/api/control"     , data : {                "keyCode" : keyCode                , "ctxWidth" : ctxWidth                , "ctxHeight" : ctxHeight                , "nowBlock" : {"O":0}     } // also, i did JSON.stringify, but did not binding..     , dataType : "json"     , contentType : "application/json"     }).done(function(data){           ... ... });然后,不要绑定“NowBlock”tetris := new(Tetris)if err := c.Bind(tetris); err != nil {    c.Logger().Error(err)}fmt.Println(tetris.NowBlock)打印结果是,'map[]' //nil...这是我的完整问题链接(GOLANG > How to bind ajax json data to custom struct type?)请帮我。附言。谢谢你回答我。我确实喜欢这个答案。但是,它也不起作用。第一的,- No 'contentType : "application/json"'- don't use JSON.stringify then, in go side, - fmt.println(tetris.KeyCode) // OK- fmt.println(tetris.NowBlock) // NOT OK.. 'map[]'第二,- Use 'contentType : "application/json"'- Use JSON.stringifythen, in go side, - fmt.println(tetris.KeyCode) // NOT OK.. '' (nil)- fmt.println(tetris.NowBlock) // NOT OK.. 'map[]'第三,i remove the custom struct type Tetris NowBlock object's `form:nowBlock` literal, but is does not working too...为什么不在地图对象中绑定自定义结构类型?
查看完整描述

2 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

你的go代码没有问题。为什么 echo.Bind()无法检索从 AJAX 发送的有效负载是因为有效负载不是 JSON 格式。


就$.ajax你需要把JSON.stringify()数据转化成JSON字符串格式。


JSON.stringify({

    "keyCode" : keyCode

    , "ctxWidth" : ctxWidth

    , "ctxHeight" : ctxHeight

    , "nowBlock" : {"O":0}

})

设置contentType为application/json不会自动将有效负载转换为 JSON 字符串。这就是为什么JSON.stringy()仍然需要。


完整的变化:


var payload = JSON.stringify({

    "keyCode": keyCode,

    "ctxWidth": ctxWidth,

    "ctxHeight": ctxHeight,

    "nowBlock": {

        "O": 0

    }

})


$.ajax({

    type: "POST",

    url: "/game/tetris/api/control",

    data: payload,

    dataType: "json",

    contentType: "application/json"

}).done(function(data) {

    ......

});


查看完整回答
反对 回复 2023-05-08
?
忽然笑

TA贡献1806条经验 获得超5个赞

也许你应该删除结构标签'form',当你使用'application/json'发送数据时,'form'标签未被使用。
当我只添加“json”标签时程序运行良好,如果我添加“form”标签,echo 使用“form”并得到一个错误。

希望这可以帮到你。


查看完整回答
反对 回复 2023-05-08
  • 2 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信