How to get multi-zone values ​​from a form using Golang?

I have several input options in my form, and I'm trying to get the selected values ​​in my handler, but I can’t, how can I get these values?

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

My handler:

 func myHandler(w http.ResponseWriter, r *http.Request) { fmt.Println(r.FormValue("new_data")) // result-> [] fmt.Println(r.Form("new_data")) // result-> [] } 

A serialized data form with parameters 1 and 2 selected from the JS console:

  >$('#myform').serialize() >"new_data=1&new_data=2" 
+6
source share
1 answer

You cannot / should not use the Request.FormValue() function because it returns only 1 value. Use Request.Form["new_data"] , which is a string fragment containing all the values.
But keep in r.FormValue() that if you do not call r.FormValue() , you need to call form parsing (and filling out the Request.Form card), explicitly calling Request.ParseForm() .

You also have an HTML syntax error: the value of the name attribute is not closed, change it to:

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

Here is the complete application to verify that it works (ommited error checking!):

 package main import ( "fmt" "net/http" ) func myHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { // Form submitted r.ParseForm() // Required if you don't call r.FormValue() fmt.Println(r.Form["new_data"]) } w.Write([]byte(html)) } func main() { http.HandleFunc("/", myHandler) http.ListenAndServe(":9090", nil) } const html = ` <html><body> <form action="process" method="post"> <select id="new_data" name="new_data" class="tag-select chzn-done" multiple="" > <option value="1">111mm1</option> <option value="2">222mm2</option> <option value="3">012nx1</option> </select> <input type="Submit" value="Send" /> </form> </body></html> ` 
+14
source

Source: https://habr.com/ru/post/982950/


All Articles