如何在Go中使用结构数据填充表单选择框?

huangapple go评论77阅读模式
英文:

How to populate form select with struct data in Go?

问题

我正在尝试使用Go语言填充一个表单选择框,我要填充的数据来自MySQL表,我已经成功地从行中创建了一个数组,现在我想要填充一个选择表单。

目标是能够从下拉菜单中选择一行,然后发送查询以从表中删除所选行。

以下是代码:

HTML

{{if .Success}}
   <h1>Your Vehicle has been successfully removed!</h1>
   <div class="divFlex">
      <button onclick="location.href = 'Add-Vehicle.html';" class="btn-block frgt_1 btn addV_btn" type="button" value="Add Another Vehicle">Add Vehicle<br>
      </button>
      <button onclick="location.href = 'Add-Vehicle.html';" class="btn-block frgt_1 btn addV_btn" type="button" value="Add Another Vehicle">Remove Vehicle</button>
   </div>
{{else}}
   <form action="/remove" method="POST" source="custom" name="form">
      <input type="hidden" name="xss-token" value=""/>
      <div class="form-group">
         <div>
            <label class="addV_label">Select Vehicle&amp;nbsp;</label>
            <select id="places" name="places">
            {{range .}}
            <option value="{{.Value}}" id="{{.Id}}" {{if .Selected}}selected{{end}}>{{.Text}}</option>
            {{end}}
            </select>
            <select name="select" class="form-control loginInput2" required="required">
               <option value="BMW">BMW</option>
            </select>
         </div>
      </div>
      <div>
         <button class="btn-block frgt_1 btn addV_btn" type="submit" value="remove">REMOVE</button>
      </div>
   </form>
{{end}}

Main.go

func RemoveVehicle(w http.ResponseWriter, r *http.Request) {

	tmpl := template.Must(template.ParseFiles("Remove-Vehicle.html"))

	db, err := sql.Open("mysql", "root:WgFl3f8218!@tcp(127.0.0.1:3306)/my_db")

	if err != nil {
		fmt.Println("Connection Failed.")
		panic(err.Error())
	}

	defer db.Close()

	// Query the DB
	var car Vehicle
	sqlStatement := `SELECT * FROM Vehicle`
	rows, err := db.Query(sqlStatement)
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	var carSlice []Vehicle
	for rows.Next() {
		rows.Scan(&car.Id, &car.Date, &car.Brand, &car.Model, &car.Mileage, &car.Year, &car.rented, &car.Dayrate)
		carSlice = append(carSlice, car)
	}

	fmt.Println(carSlice)

	// insert, err := db.Query("INSERT INTO vehicle(id, date, brand, model, mileage, manufactured, rented, dayrate) VALUES ( ?, NOW(), ?, ?, ?, ?, 0, ?)", id.String(), brand_, model_, mileage_, year_, dayrate_)
	// if err != nil {
	// 	panic(err.Error())
	// }
	// defer insert.Close()

	// tmpl.Execute(w, struct {
	// 	Success bool
	// 	Brand   string
	// 	Model   string
	// 	Year    int64
	// 	Mileage int64
	// 	Dayrate int64
	// }{true, brand_, model_, year_, mileage_, dayrate_})
}

我还注意到另一个问题是表单的方法是POST,因为我看到了一些例子中表单的方法是GET。

我需要在页面加载时填充选择框,然后从表中删除匹配的选项。

英文:

I am trying to find a way to populate a form select with Go, the data I am trying to populate is taking from a MySQL table, I have already managed to create an array from the rows, I am now looking to populate a select form.

The goal is to be able to select a row from the drop down, to then send a query to delete the selected row from the table.

Below is the code:

HTML

                        {{if .Success}}
                           &lt;h1&gt;Your Vehicle has been successfully removed!&lt;/h1&gt;
                           &lt;div class=&quot;divFlex&quot;&gt;
                              &lt;button onclick=&quot;location.href = &#39;Add-Vehicle.html&#39;;&quot; class=&quot;btn-block frgt_1 btn addV_btn&quot; type=&quot;button&quot; value=&quot;Add Another Vehicle&quot;&gt;Add Vehicle&lt;br&gt;
                              &lt;/button&gt;
                              &lt;button onclick=&quot;location.href = &#39;Add-Vehicle.html&#39;;&quot; class=&quot;btn-block frgt_1 btn addV_btn&quot; type=&quot;button&quot; value=&quot;Add Another Vehicle&quot;&gt;Remove Vehicle&lt;/button&gt;
                           &lt;/div&gt;
                        {{else}}
                           &lt;form action=&quot;/remove&quot; method=&quot;POST&quot; source=&quot;custom&quot; name=&quot;form&quot;&gt;
                              &lt;input type=&quot;hidden&quot; name=&quot;xss-token&quot; value=&quot;&quot;/&gt;
                              &lt;div class=&quot;form-group&quot;&gt;
                                 &lt;div&gt;
                                    &lt;label class=&quot;addV_label&quot;&gt;Select Vehicle&amp;nbsp;&lt;/label&gt;
                                    &lt;select id=&quot;places&quot; name=&quot;places&quot;&gt;
                                    {{range .}}
                                    &lt;option value=&quot;{{.Value}}&quot; id=&quot;{{.Id}}&quot; {{if .Selected}}selected{{end}}&gt;{{.Text}}&lt;/option&gt;
                                    {{end}}
                                    &lt;/select&gt;
                                    &lt;select name=&quot;select&quot; class=&quot;form-control loginInput2&quot; required=&quot;required&quot;&gt;
                                       &lt;option value=&quot;BMW&quot;&gt;BMW&lt;/option&gt;
                                    &lt;/select&gt;
                                 &lt;/div&gt;
                              &lt;/div&gt;
                              &lt;div&gt;
                                 &lt;button class=&quot;btn-block frgt_1 btn addV_btn&quot; type=&quot;submit&quot; value=&quot;remove&quot;&gt;REMOVE&lt;/button&gt;
                              &lt;/div&gt;
                           &lt;/form&gt;
                        {{end}}

Main.go

func RemoveVehicle(w http.ResponseWriter, r *http.Request) {

	tmpl := template.Must(template.ParseFiles(&quot;Remove-Vehicle.html&quot;))

	db, err := sql.Open(&quot;mysql&quot;, &quot;root:WgFl3f8218!@tcp(127.0.0.1:3306)/my_db&quot;)

	if err != nil {
		fmt.Println(&quot;Connection Failed.&quot;)
		panic(err.Error())
	}

	defer db.Close()

	// Query the DB
	var car Vehicle
	sqlStatement := `SELECT * FROM Vehicle`
	rows, err := db.Query(sqlStatement)
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	var carSlice []Vehicle
	for rows.Next() {
		rows.Scan(&amp;car.Id, &amp;car.Date, &amp;car.Brand, &amp;car.Model, &amp;car.Mileage, &amp;car.Year, &amp;car.rented, &amp;car.Dayrate)
		carSlice = append(carSlice, car)
	}

	fmt.Println(carSlice)

	// insert, err := db.Query(&quot;INSERT INTO vehicle(id, date, brand, model, mileage, manufactured, rented, dayrate) VALUES ( ?, NOW(), ?, ?, ?, ?, 0, ?)&quot;, id.String(), brand_, model_, mileage_, year_, dayrate_)
	// if err != nil {
	// 	panic(err.Error())
	// }
	// defer insert.Close()

	// tmpl.Execute(w, struct {
	// 	Success bool
	// 	Brand   string
	// 	Model   string
	// 	Year    int64
	// 	Mileage int64
	// 	Dayrate int64
	// }{true, brand_, model_, year_, mileage_, dayrate_})
}

Another issue I see is that the form method being POST, as I've seen a few examples in which the form method is GET.

I need to be able to populate select on page load, and then remove the matching option from the table.

答案1

得分: 1

你可以同时使用POST和GET方法,但它们用于不同的目的。

GET和POST的解释

此外,你可以查看下面的链接,了解如何在Go服务器中使用内置的http包处理POST和GET请求。

处理GET和POST请求的示例

英文:

You can use both POST and GET method but they serve for different purposes.

GET and POST explained

Also you can check the link below to see how POST and GET requests are handled in Go server with built-in http package.

Get and Post request handled

huangapple
  • 本文由 发表于 2022年1月29日 00:38:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/70897119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定