亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否可以綁定到自定義結構類型的地圖對象?

是否可以綁定到自定義結構類型的地圖對象?

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 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號