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

我的问题是,如何在地图对象(变量)中绑定(自动绑定?)自定义结构类型?


这是我的自定义结构类型


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.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...

为什么不在地图对象中绑定自定义结构类型?


慕侠2389804
浏览 68回答 2
2回答

莫回无

你的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) {    ......});

忽然笑

也许你应该删除结构标签'form',当你使用'application/json'发送数据时,'form'标签未被使用。当我只添加“json”标签时程序运行良好,如果我添加“form”标签,echo 使用“form”并得到一个错误。希望这可以帮到你。
打开App,查看更多内容
随时随地看视频慕课网APP