更新时间:2022-07-01 11:52:29
用Beego来进行web开发,对每个页面都可创建一个YourController类型,并匿名包含beego.Controller来达到继承beego.Controller的效果。以YourController为receiver重写beego.Controller的Get,Post等方法。当网页请求为Get/Post,则执行该页面YourController的Get()/Post()方法。
在对应页面的Controller的Get()方法中,往数据Data写入category的实例切片cates:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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模板中:
1
2
3
4
5
6
|
< 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,页面渲染如下截图:
在上图中,点击“提交”按钮,客户端向服务器发送Post请求,让我们看下该页面的Post表单:
我们看到,form表单中,select组件设置id,name为“category”,当用户点击了“提交”,向服务器发送Post请求提交该表单,Beego中该页面Controller的Post()方法可通过this.input().Get("category")来过得select中category的value值,这些值就是被选中option的value值:
1
2
3
4
5
6
7
8
|
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,点击“提交”,后台输出:
注意,select默认值是最上面的请选择,故再击提交按钮时要通过html页面内javascript函数 check();"来判断select是否做出正确选择,check()为一个hmtl嵌套的js脚本函数:
1
2
3
4
5
6
7
8
|
function check() {
if ( '-1' == $( '#category' ).val()) { //select的value值为-1
alert( "请选择文章创作类型" );
$( '#category' ).focus();
return false ;
}
return true ;
}
|