[英]Golang Get all POST Form data using PostParams and get values as string
我想獲取所有發布表單數據並將值作為字符串獲取,但是使用 PostParams 我能夠獲取所有發布數據,但值作為數組鍵:[value],如何獲取所有表單數據作為字符串值?
[編輯] 我可能沒有說清楚,但我需要將整個表格作為 JSON,因為我需要將表格數據發送到另一個 API,它需要正文作為 JSON 數據
表格.html
<form>
<input type='text' name='key' />
<input type='text' name='key2' />
</form>
腳本.js
$.ajax( {
url: '/post/action',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false
}).done(function(r) {
console.log(r);
});
行動.go
func PostAction(c echo.Context) error {
form, _ := c.FormParams()
b, _ := json.Marshal(form)
log.Println(b) // this will print: key: [value], key2: [value]
// I want to get value as string: key: value, key2: value
// ..other function, return, etc
}
如何將表單值作為字符串獲取? 或者是否有另一個 function 這樣做?
非常感謝你提前
無需 JSON 編組已經解碼的形式,只需執行以下操作:
form["key"][0]
form["key2"][0]
請參閱c.FormParams
上的文檔,然后單擊返回類型以查看其文檔,您會注意到它只是 stdlib 的url.Values
類型,它被定義為 map 的字符串切片(即map[string][]string
)。
如果需要將類型為url.Values
的值轉換為“簡單對象”,可以使用以下代碼將其轉換為map[string]string
:
o := make(map[string]string, len(form))
for k, v := range form {
// if you are certain v[0] is present
o[k] = v[0]
// if you are not sure v[0] is present, check first
if len(v) > 0 {
o[k] = v[0]
}
}
data, err := json.Marshal(o)
if err != nil {
return err
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.