摘要:本节主要是关于post请求获取数据以及起来格式数据渲染方式(json、xml等)
2、Post请求
//获取请求消息
//router.go
beego.Router("/add_user",&controllers.UserController)
//user.html
<form action="add_user" method="post">
用户名:<input type="text" name="user_name">
密码:<input type="password" name="password">
<input type="sumbit" value="提交">
</form>
//user.go
func (u *UserController) Post(){
user := u.GetString("user_name")
passwd := u.GetString("password")
fmt.Println(user)
fmt.Println(passwd)
u.Ctx.WriteString("提交成功")
}
----------------------------------------------------------------------------
//form表单解析到结构体
//router.go
beego.Router("/add_user",&controllers.UserController)
//user.html
<form action="add_user" method="post">
用户名:<input type="text" name="user_name">
密码:<input type="password" name="password">
<input type="sumbit" value="提交">
</form>
//user.go
type student struct{
Id int
Name string `form:"user_name"`
Password string `form:"password"`
}
func (u *UserController) Post(){
student := Student{}
u.ParseForm(&student)
fmt.Println(student.Name)
fmt.Println(student.Password)
u.Ctx.WriteString("提交成功")
}
----------------------------------------------------------------------------
//获取ajax数据
//router.go
beego.Router("/add_user_ajax",&controllers.UserController)
//user.html
<form id="add_user">
用户名:<input type="text" id="user_name">
密码:<input type="password" id="password">
<input type="button" value="提交">
</form>
//user.go
type student struct{
Id int
Name string `form:"user_name"`
Password string `form:"password"`
}
func (u *UserController) Post(){
student := Student{}
u.ParseForm(&student)
fmt.Println(student.Name)
fmt.Println(student.Password)
u.Ctx.WriteString("提交成功")
}
二、其他格式数据渲染方法
1、json格式:会设置 content-type 为 application/json
type TestController struct {
beego.Controller
}
type Person struct {
Id int
Name string
Gender string
}
func (g *TestController)Get() {
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["json"] = &test_data
fmt.Println(test_data)
g.ServeJSON()
//g.TplName = "test.html"
}
2、xml格式:会设置 content-type 为 application/xml
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["xml"] = &test_data
g.ServeXML()
3、jsonp格式:会设置 content-type 为 application/javascript
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["jsonp"] = &test_data
g.ServeJSONP()
4、yaml格式:会以文件传输的方式,yaml就是键值对
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["yaml"] = &test_data
g.ServeYAML()