卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34874本站已运行393

Go 代码不打印来自 jquery ajax 的已发布 json 值

go 代码不打印来自 jquery ajax 的已发布 json 值

php小编新一分享一种解决方案,帮助你在Go代码中避免打印来自jquery ajax已发布的json值。通过这种方法,你可以有效地控制打印输出,确保代码的可读性和安全性。无论是在前端还是后端开发中,这个技巧都非常实用,帮助你更好地处理json数据。让我们一起来看看具体的实现方法吧!

问题内容

问题详细信息

go 代码未打印来自 jquery ajax 的已发布 json 值

转到代码主

routing := chi.newrouter()
routing.post("/authenticate", authenticaterouter)

go代码

func authenticaterouter(w http.responsewriter, r *http.request) {
    username := r.postform.get("username")
    fmt.println(r.postformvalue("username"))  //not showing posted value
    fmt.println(r.form.get("username"))       //not showing posted value
    fmt.println(r.form.get("username"))       //not showing posted value
}

jquery ajax 代码

$.ajax({
    "type": "post",
    "url": "authenticate",
    "contenttype": "application/json; charset=utf-8",
    "datatype": "json",
    "data": json.stringify({
        "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;
    }
});

html

<form class="loginForm form-signin"><br>    
    <input type="text" name="username" />
    <input type="password" name="password" />
    <button type="submit">Log In</button>
</form>

解决方法

您正在发送 json 数据,但 postform 使用 url 编码数据。你可以这样做:

type authBody struct {
   Username string `json:"username"`
   Password string `json:"password"`
}

func AuthenticateRouter(w http.ResponseWriter, r *http.Request) {
   dec:=json.NewDecoder(r.Body)
   var body authBody
   if err:=dec.Decode(&body); err!=nil {
      // deal with err
   }
   // Work with body.Username and body.Password
}
卓越飞翔博客
上一篇: 如何使用 Chi 路由器提供静态文件夹服务
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏