首页 > 文章列表 > 使用PostParams获取所有POST表单数据的字符串值

使用PostParams获取所有POST表单数据的字符串值

172 2024-02-09
问题内容

我想获取所有帖子表单数据并将值作为字符串获取,但是使用 postparams 我能够获取所有帖子数据,但值作为数组键:[value],我怎样才能获取所有将数据形成为字符串值?

[编辑] 我可能没有明确说明,但我需要将整个表单作为 json 获取,因为我需要将表单数据发送到另一个需要正文作为 json 数据的 api

表单.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
}

如何获取字符串形式的值? 或者还有其他函数可以做到这一点吗?

提前非常感谢


正确答案


无需对已解码的表单进行 json 编组,只需执行以下操作:

form["key"][0]
form["key2"][0]

请参阅 c.formparams 上的文档然后单击返回类型查看其文档,您会注意到它只是 stdlib 的 url.values 类型,它被定义为字符串切片的映射(即 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
}

// ...