Go代码无法打印JQuery Ajax提交的JSON值问题排查
问题解决:Go无法获取jQuery Ajax提交的JSON值
问题根源
你前端设置了contentType: "application/json",将数据以JSON字符串格式提交,但Go的r.PostForm、r.PostFormValue、r.Form.Get这类方法仅用于解析**表单编码(application/x-www-form-urlencoded)**的请求体,无法直接读取JSON格式的数据,因此拿不到username的值。
解决方案
提供两种可行方案,可根据需求选择:
方案一:修改Go后端解析JSON请求体
定义对应结构体接收JSON数据,使用encoding/json包解析请求体:
import ( "encoding/json" "fmt" "net/http" ) // 定义结构体匹配JSON字段 type AuthRequest struct { Username string `json:"username"` Password string `json:"password"` } func AuthenticateRouter(w http.ResponseWriter, r *http.Request) { var req AuthRequest // 解析请求体到结构体 err := json.NewDecoder(r.Body).Decode(&req) if err != nil { http.Error(w, "无效的请求数据", http.StatusBadRequest) return } defer r.Body.Close() // 正常获取提交的值 fmt.Println(req.Username) fmt.Println(req.Password) }
方案二:修改前端Ajax以表单编码提交
若不想改动后端,可调整前端提交格式,使用默认的表单编码:
$.ajax({ "type": "post", "url": "authenticate", // 移除contentType,jQuery默认采用application/x-www-form-urlencoded编码 "dataType": "json", "data": { "username": $(form).find("[name='username']").val(), "password": $(form).find("[name='password']").val(), }, beforeSend: function() {}, success: function(response) { debugger; }, error: function(response) { debugger; }, complete: function(response) { debugger; } });
调整后,后端原有的r.PostForm.Get("username")即可正常获取提交的值。
内容的提问来源于stack exchange,提问作者Pankaj
相关产品推荐
相关产品推荐

