我的问题是,如何在地图对象(变量)中绑定(自动绑定?)自定义结构类型?
这是我的自定义结构类型
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)
println 结果是 ,
'map[]' //nil...
这是我的完整问题链接(GOLANG > 如何将 ajax json 数据绑定到自定义结构类型?)
请帮我。
附言。谢谢你回答我。我确实喜欢这个答案。但是,它也不起作用。
第一的,
- 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.stringify
then, 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...
为什么不在地图对象中绑定自定义结构类型?
我很抱歉。我解决了这个问题。问题是我的自定义结构类型有另一个自定义结构类型。
像这样。
type Tetris struct {
Common Common
NowBlock map[string]int `json:"nowBlock"`
}
type Common struct {
CtxWidth int `json:"ctxWidth"`
CtxHeight int `json:"ctxHeight"`
KeyCode int `form:"keyCode" json:"keyCode"`
}
在这种情况下,我做到了
$.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){
... ...
});
但是,这是错误的!正确的是,
$.ajax({
type : "POST"
, url : "/game/tetris/api/control"
, data : JSON.stringify({
"Common" : {
"keyCode" : keyCode
, "ctxWidth" : ctxWidth
, "ctxHeight" : ctxHeight
}
, "nowBlock" : {"O":0}
})
, dataType : "json"
, contentType : "application/json"
}).done(function(data){
... ...
在 json 数据中,“Common”结构类型的数据必须具有“Common”“Key:value”映射...
我很高兴您的回答和关注。