Categories: Gin 教程

Gin 绑定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})
}

唐伯虎点蚊香

前端小白,想各位学习!

Share
Published by
唐伯虎点蚊香

Recent Posts

vue:页面注入js修改input值

一般会直接这样写: let z…

5 小时 ago

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago