首頁  >  文章  >  後端開發  >  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刪除