Go Code无法从jquery AJAX 打印已发布的json值

91zkwejq  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(124)

发行详情

Go Code无法从jquery AJAX 打印已发布的json值

Go Code Main

routing := chi.NewRouter()
routing.Post("/authenticate", AuthenticateRouter)

字符串

Go Code

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;
    }
});


联系我们

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

neskvpey

neskvpey1#

您正在发送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
}

字符串

相关问题