首页  >  文章  >  后端开发  >  Go 代码不打印来自 jquery ajax 的已发布 json 值

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

WBOY
WBOY转载
2024-02-09 14:30:09808浏览

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
}

以上是Go 代码不打印来自 jquery ajax 的已发布 json 值的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除