• 绑定 HTML 复选框

    绑定 HTML 复选框

    参见详细信息

    main.go

    1. ...
    2. type myForm struct {
    3. Colors []string `form:"colors[]"`
    4. }
    5. ...
    6. func formHandler(c *gin.Context) {
    7. var fakeForm myForm
    8. c.ShouldBind(&fakeForm)
    9. c.JSON(200, gin.H{"color": fakeForm.Colors})
    10. }
    11. ...

    form.html

    1. <form action="/" method="POST">
    2. <p>Check some colors</p>
    3. <label for="red">Red</label>
    4. <input type="checkbox" name="colors[]" value="red" id="red">
    5. <label for="green">Green</label>
    6. <input type="checkbox" name="colors[]" value="green" id="green">
    7. <label for="blue">Blue</label>
    8. <input type="checkbox" name="colors[]" value="blue" id="blue">
    9. <input type="submit">
    10. </form>

    结果:

    1. {"color":["red","green","blue"]}