如何使用 Golang 从表单中获取多选值?

我的表单中有一个多选输入,我试图在我的处理程序中获取选定的值,但我不能,我怎样才能获取这些值?


<form action="process" method="post">

    <select id="new_data" name="new_data class="tag-select chzn-done" multiple="" style="display: none;">

    <option value="1">111mm1</option>

    <option value="2">222mm2</option>

    <option value="3">012nx1</option>

    </select>

</form>

我的处理程序:


func myHandler(w http.ResponseWriter, r *http.Request) {

    fmt.Println(r.FormValue("new_data")) // result-> []

    fmt.Println(r.Form("new_data")) // result-> []

}

从 JS 控制台选择选项 1 和 2 的表单序列化数据:


   >$('#myform').serialize() 

   >"new_data=1&new_data=2"


梦里花落0921
浏览 288回答 1
1回答

翻阅古今

您不能/不应该使用该Request.FormValue()函数,因为它只返回 1 个值。使用包含所有值Request.Form["new_data"]的strings切片。但请注意,如果您不调用r.FormValue(),则必须Request.Form通过Request.ParseForm()显式调用来触发解析表单(并填充地图)。您还有一个 HTML 语法错误:name属性的值未关闭,将其更改为:<select id="new_data" name="new_data" class="tag-select chzn-done"&nbsp; &nbsp; multiple="" style="display: none;">这是一个完整的应用程序来测试它是否有效(省略错误检查!):package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "net/http")func myHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; if r.Method == "POST" {&nbsp; &nbsp; &nbsp; &nbsp; // Form submitted&nbsp; &nbsp; &nbsp; &nbsp; r.ParseForm() // Required if you don't call r.FormValue()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(r.Form["new_data"])&nbsp; &nbsp; }&nbsp; &nbsp; w.Write([]byte(html))}func main() {&nbsp; &nbsp; http.HandleFunc("/", myHandler)&nbsp; &nbsp; http.ListenAndServe(":9090", nil)}const html = `<html><body><form action="process" method="post">&nbsp; &nbsp; <select id="new_data" name="new_data" class="tag-select chzn-done" multiple="" >&nbsp; &nbsp; &nbsp; &nbsp; <option value="1">111mm1</option>&nbsp; &nbsp; &nbsp; &nbsp; <option value="2">222mm2</option>&nbsp; &nbsp; &nbsp; &nbsp; <option value="3">012nx1</option>&nbsp; &nbsp; </select>&nbsp; &nbsp; <input type="Submit" value="Send" /></form></body></html>`
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go