AdSense

網頁

2022/6/25

Golang Web接收表單複選框多筆值

Go HTTP Web接收HTML表單複選框的多資料。


範例環境:

  • Go 1.18


表單

下面HTML表單的languages欄位為複選框,欄位名稱name="lang"

demo.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <form action="http://localhost:8080/employee" method="POST">
        name:<input name="name" type="text" value="John"><br>
        languages:
            <label><input type="checkbox" name="lang" value="en" checked>english</label>
            <label><input type="checkbox" name="lang" value="ch" checked>mandarin</label>
            <label><input type="checkbox" name="lang" value="jp" checked>japanese</label>
        <br>
        <input type="submit">
    </form>
</body>
</html>


取得表單複選框值

下面POST|/employee API接收表單資料。先調用http.Requset.ParseForm()然後以複選框欄位名稱lang為key從http.Request.Form(型態為url.Values,實為map[string][]string)取得language複選框值為[]string

main.go

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/employee", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodPost:
            r.ParseForm()
            name := r.Form.Get("name")
            langs := r.Form["lang"]

            fmt.Fprint(w, fmt.Sprintf(
                "name=%v\nlanguages=%v",
                name, langs))
        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }
    })
    http.ListenAndServe(":8080", nil)
}


測試

啟動專案,在瀏覽器開啟表單輸入資料如下。

name:
languages:

點選Submit提交結果如下。





沒有留言:

AdSense