教程 > Gin 教程 > Gin 基础 阅读:23

Gin 绑定HTML复选框

前端代码

form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/" method="POST">
        <p>Check some colors</p>
        <label for="red">Red</label>
        <input type="checkbox" name="colors[]" value="red" id="red" />
        <label for="green">Green</label>
        <input type="checkbox" name="colors[]" value="green" id="green" />
        <label for="blue">Blue</label>
        <input type="checkbox" name="colors[]" value="blue" id="blue" />
        <input type="submit" />
    </form>
</body>
</html>

Gin框架代码

package main

import (
    "github.com/gin-gonic/gin"
)

type myForm struct {
    Colors []string `form:"colors[]"`
}

func main() {
    r := gin.Default()

    r.LoadHTMLGlob("views/*")
    r.GET("/", indexHandler)
    r.POST("/", formHandler)

    r.Run(":8080")
}

func indexHandler(c *gin.Context) {
    c.HTML(200, "form.html", nil)
}

func formHandler(c *gin.Context) {
    var fakeForm myForm
    c.Bind(&fakeForm)
    c.JSON(200, gin.H{"color": fakeForm.Colors})
}

Gin 绑定HTML复选框

查看笔记

扫码一下
查看教程更方便