使用Golang和Bootstrap时,表单数据始终为空

时间:2019-11-30 05:34:30

标签: go

因此,我尝试使用引导程序创建一个表单,并在golang中对其进行解析,但是表单数据始终返回为空。

Golang:

   // CreateEmployee - handler function for creating a new employee
func CreateEmployee(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(r.Form)
}

引导程序表单:

<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
    <form action="/employee" method="post">
        <div class="form-group">
            <label>Name</label>
            <input type="text" id="name" class="form-control" placeholder="Enter name">
        </div>
        <div class="form-group">
            <label>Title</label>
            <input type="text" id="title" class="form-control" placeholder="Enter title">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" id="email" class="form-control" placeholder="Enter email">
        </div>
        <div class="form-group">
            <label>Photo</label>
            <input type="text" id="photo" class="form-control" placeholder="Enter photo 
             location">
        </div>
        <div class="form-group">
            <label>Phonetic</label>
            <input type="text" id="phonetic" class="form-control" placeholder="Enter 
              phonetic pronunciation">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
</body>

我知道您必须在r.Form填充之前调用ParseForm,但据我所知,这就是必需的。

该路线工作正常,因为当我提交表单时,它正在向控制台打印一个空地图。看来我在做一些愚蠢的事情,但无法弄清楚。

1 个答案:

答案 0 :(得分:2)

<input>元素中缺少name属性。如果name属性未设置或为空,则输入值不包含在提交的表单中。

修复如下:

    <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" id="name" class="form-control" placeholder="Enter name">
    </div>

...,其他输入元素依此类推。