首頁 > 後端開發 > Golang > 主體

Go 程式碼不會列印來自 jquery ajax 的已發布 json 值

WBOY
發布: 2024-02-09 14:30:09
轉載
809 人瀏覽過

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!