您的位置:首页 > Web前端 > HTML

golang Beego框架之HTML表单中的select标签组件的处理 推荐

2014-02-10 22:19 1266 查看
用Beego来进行web开发,对每个页面都可创建一个YourController类型,并匿名包含beego.Controller来达到继承beego.Controller的效果。以YourController为receiver重写beego.Controller的Get,Post等方法。当网页请求为Get/Post,则执行该页面YourController的Get()/Post()方法。
在对应页面的Controller的Get()方法中,往数据Data写入category的实例切片cates:

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模板中:
<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值:
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脚本函数:
function check() {
if ('-1' == $('#category').val()) {//select的value值为-1
alert("请选择文章创作类型");
$('#category').focus();
return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐