【问题标题】:How to bind a checkbox in Echo framework?如何在 Echo 框架中绑定复选框?
【发布时间】:2020-07-30 08:43:44
【问题描述】:

我有一个简单的表单,我想在发布请求上绑定它。

这是表格:

<form method="post" action="/post">
    <input type="text" name="name" placeholder="name"><br>
    <input type="checkbox" name="agree"><br>
    <button type="submit">submit</button>
</form>

我正在尝试将它绑定在这样的结构中:

type PostForm struct {
    Name  string
    Agree bool
}

这是整个代码:

package main

import (
    "github.com/labstack/echo/v4"
    "html/template"
    "io"
    "log"
    "net/http"
)

type Template struct {
    templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, _ echo.Context) error {
    return t.templates.ExecuteTemplate(w, name, data)
}

type PostForm struct {
    Name  string
    Agree bool
}

func main() {
    e := echo.New()
    e.Debug = true
    e.Renderer = &Template{
        templates: template.Must(template.ParseGlob("./templates/*.gohtml")),
    }
    e.GET("/", func(c echo.Context) error {
        return c.Render(http.StatusOK, "index.gohtml", nil)
    })
    e.POST("/post", func(c echo.Context) error {
        var form PostForm
        err := c.Bind(&form)
        if err != nil {
            return c.String(http.StatusInternalServerError, err.Error())
        }
        return c.JSON(http.StatusOK, form)

    })

    log.Fatalln(e.Start(":3000"))
}

当我使用未选中的同意字段发布请求时,它工作正常:

{
  "Name": "sdfgsdfg",
  "Agree": false
}

但是当我发送带有选中复选框的帖子时,出现错误:

code=400, message=strconv.ParseBool: parsing "on": invalid syntax, internal=strconv.ParseBool: parsing "on": invalid syntax

我做错了什么?

这里是 github 上的所有代码:https://github.com/max-block/q__echo_bind_checkbox

【问题讨论】:

    标签: go web


    【解决方案1】:
    <html>
    <head></head>
    <body>
    <form method="post" action="/post">
        <input type="text" name="name" placeholder="name"><br>
        // set the value as "true"
        <input type="checkbox" name="agree" value="true"><br>
        <button type="submit">submit</button>
    </form>
    </body>
    </html>
    

    checkbox的默认值为“on”,与go的“true”不同。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      相关资源
      最近更新 更多