注意:是post请求
一、获取表单提交的数据1.contxt.PostForm(“username”) 获取表单中的name属性对应的值
示例代码:
前端:submit提交后端: func IndexAdd(contxt *gin.Context) { name := contxt.PostForm("username") age := contxt.PostForm("age") contxt.String(200,"hello,%s,年龄为:%s",name,age) } func main() { engine := gin.Default() engine.LoadHTMLGlob("templates*") engine.Static("/static","static") engine.POST("/hello_add",IndexAdd) engine.Run() }
2.contxt.DefaultPostForm(“username”, “hallen”) 如果没有获取到则使用指定的默认值
3.contxt.PostFormArray(“love”) 如果提交的数据有多个相同的name,获取数组
前端:后端: arr_ck := contxt.PostFormArray("ck")
- contxt.PostFormMap(“username”)
前端代码:后端代码: map_name := contxt.PostFormMap("username") 数据结构:map[1:xx1 2:xx2] 注意:name要以map的格式定义,指定key,用户输入value, 二、ajax交互
前端使用ajax提交,后端和form表单的获取方式一样,唯一的区别就是返回的是json
前端:注意:引入jquery.min.js: 后端: name := context.PostForm("name") age := context.PostForm("age") fmt.Println(name) fmt.Println(age) messgae_map := map[string]interface{}{ "code":200, "msg":"提交成功", } context.JSON(http.StatusOK,messgae_map) //context.JSON(http.StatusOK,gin.H{ // "code":200, // "msg":"提交成功", //})



