日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Go gin获取post请求数据

發(fā)布時間:2025/1/21 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Go gin获取post请求数据 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Go gin獲取post請求數(shù)據(jù)

注意:是post請求

一、獲取表單提交的數(shù)據(jù)

1.contxt.PostForm(“username”) 獲取表單中的name屬性對應(yīng)的值

示例代碼:

前端:submit提交 <form action="/hello_add" method="post"><input type="text" name="username"><br><input type="text" name="age"><br><input type="submit" value="提交"> </form>后端: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”) 如果沒有獲取到則使用指定的默認(rèn)值

3.contxt.PostFormArray(“l(fā)ove”) 如果提交的數(shù)據(jù)有多個相同的name,獲取數(shù)組

前端: <form action="/hello_add" method="post"><input type="text" name="username"><br><input type="text" name="age"><br>ck1:<input type="checkbox" name="ck" value="1">ck2:<input type="checkbox" name="ck" value="2">ck3:<input type="checkbox" name="ck" value="3"><input type="submit" value="提交"> </form>后端: arr_ck := contxt.PostFormArray("ck")
  • contxt.PostFormMap(“username”)
  • 前端代碼: <form action="/hello_add" method="post"><input type="text" name="username[1]"><br><input type="text" name="username[2]"><br><input type="submit" value="提交"> </form>后端代碼: map_name := contxt.PostFormMap("username")數(shù)據(jù)結(jié)構(gòu):map[1:xx1 2:xx2]注意:name要以map的格式定義,指定key,用戶輸入value,

    二、ajax交互

    前端使用ajax提交,后端和form表單的獲取方式一樣,唯一的區(qū)別就是返回的是json

    前端:<script src="/static/js/jquery.min.js"></script> <form>姓名:<input type="text" id="name">年齡:<input type="text" id="age"><input type="button" value="提交" id="btn_add"> </form><script>var btn_add = document.getElementById("btn_add");btn_add.onclick = function (ev) {var name = document.getElementById("name").value;var age = document.getElementById("age").value;$.ajax({url:"/hello3_add",type:"POST",data:{"name":name,"age":age},success:function (data) {alert(data["code"]);alert(data["msg"]);},fail:function (data) {}})}</script>注意:引入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":"提交成功", //})

    總結(jié)

    以上是生活随笔為你收集整理的Go gin获取post请求数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。