用Beego來進行web開發,對每一個頁面均可建立一個YourController類型,並匿名包含beego.Controller來達到繼承beego.Controller的效果。以YourController爲receiver重寫beego.Controller的Get,Post等方法。當網頁請求爲Get/Post,則執行該頁面YourController的Get()/Post()方法。javascript
在對應頁面的Controller的Get()方法中,往數據Data寫入category的實例切片cates:
html
func(this *YourController)Get() { this.TplNames = "yourPage.html" cates := []*category{ &category{"-1", true, "請選擇"}, &category{"golang", false, "golang"}, &category{"Java", false, "Java"}, &category{"C/C++", false, "C/C++"}, } this.Data["Cates"] = cates } type category struct { Id string IsSelected bool Value string }
對應的HTML模板中:java
<select class="form-control input-sm" name="category" id="category" style="width: 120px;"> `range `.`Cates` <option value=``.`Id` `if `.`IsSelected` select="selected"`end`>``.`Value`</option> `end` </select>
HTML中用`range `.`Cates`來遍歷golang傳來的Data(此處.Cates傳來的是Get方法中的Data["Cates"]),而``.`Id`,``.`IsSelected`,``.`Valuse`分別爲golang中的類型category的三個字段。當Method爲Get,頁面渲染以下截圖:golang
在上圖中,點擊「提交」按鈕,客戶端向服務器發送Post請求,讓咱們看下該頁面的Post表單:
web
咱們看到,form表單中,select組件設置id,name爲「category」,當用戶點擊了「提交」,向服務器發送Post請求提交該表單,Beego中該頁面Controller的Post()方法可經過this.input().Get("category")來過得select中category的value值,這些值就是被選中option的value值:服務器
func (this *YourController) Post() { this.TplNames = "yourPage.html" this.Ctx.Request.ParseForm() category := this.Input().Get("category") fmt.Println("caterogy value:", category) this.Redirect("/category", 301) return }
選擇golang,點擊「提交」,後臺輸出:
ide
注意,select默認值是最上面的請選擇,故再擊提交按鈕時要經過html頁面內javascript函數 check();"來判斷select是否作出正確選擇,check()爲一個hmtl嵌套的js腳本函數:函數
function check() { if ('-1' == $('#category').val()) {//select的value值爲-1 alert("請選擇文章創做類型"); $('#category').focus(); return false; } return true; }