代码之家  ›  专栏  ›  技术社区  ›  Pankaj

Go Code没有打印jquery ajax中发布的json值

  •  0
  • Pankaj  · 技术社区  · 3 年前

    问题详细信息

    Go Code没有打印jquery ajax中发布的json值

    Go Code Main

    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>
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Burak Serdar    3 年前

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