本教材由知了传课辛苦制作而成,仅供学习使用,请勿用于商业用途!如进行转载请务必注明出处!谢谢!

获取请求数据

获取url上的参数,?后面的 :http://127.0.0.1:8090/user/?id=111
** 可以使用数据绑定,请看数据绑定章节**
GetString获取数据: 路由: beego.Router("/user", &controllers_user.UserController{}) 访问路径:http://127.0.0.1:8090/user/?id=111 获取数据: id := c.Input().Get("id") id2 := c.GetString("id") 这种方式不行: id3 := c.Ctx.Input.Param(":id")
获取url上的参数,/:id的 :http://127.0.0.1:8090/user/111
路由:beego.Router("/user/?:id:int", &controllers_user.UserController{}) 访问路径:http://127.0.0.1:8090/user/111 获取数据: id := c.GetString(":id") id2 := c.Ctx.Input.Param(":id") 这种方式不行: id3 := c.Input().Get(":id")
获取请求信息:
this.Ctx.Request 所有的请求信息 this.Ctx.Request.Header 请求头 this.Ctx.Request.Host 请求的主机 this.Ctx.Request.Method 请求的方法
获取form表单数据:
GetString(key string) string GetStrings(key string) []string GetInt(key string) (int64, error) --返回两个值 GetBool(key string) (bool, error) --返回两个值 GetFloat(key string) (float64, error) --返回两个值 举例: 前端form表单: <form action="/user" method="post"> 年龄1:<input type="text" name="age"><br> 姓名1:<input type="text" name="name"><br> 地址:<input type="text" name="addr"><br> 姓名2:<input type="text" name="name"><br> 年龄2:<input type="text" name="age"><br> 是:<input type="radio" name="is_true" value="true"> 否:<input type="radio" name="is_true" value="false"><br> 价格:<input type="text" name="price"><br> <input type="submit" value="提交"><br> </form> 获取数据: name := c.Input().Get("name") 获取的是第一个name的值 names := c.GetStrings("name") 获取所有的name的值,是个数组 age := c.Input().Get("age") age,_ := c.GetInt64("age") is_true , _ := c.GetBool("is_true") price , _ := c.GetFloat("price")

form表单解析到结构体

type Student struct { Id int Name string `form:"user_name"` Password string `form:"password"` } func (s *StudentController) Post() { student := Student{} // 这里注意,变量名不能和结构体对象名不能相同 if err := s.ParseForm(&student); err != nil { //handle error return } fmt.Println(student) fmt.Println(student.Name) fmt.Println(student.Age) fmt.Println(student.Addr) s.TplName = "index.tpl" }

ajax提交

<script src="/static/js/jquery.min.js"></script> <script> var add_student = document.getElementById("add_student"); add_student.onclick = function (ev) { var user_name = document.getElementById("user_name").value; var password = document.getElementById("password").value; $.ajax({ url:"/add_user_ajax", type:"POST", data:{ "user_name":user_name, "password":password }, success:function (data) { if(data["code"] == 200){ alert(data["msg"]) }else { alert("添加失败") } }, fail:function (data) { } }) } </script>

1618人已阅读,今天你学习了吗?

添加新回复