Home  >  Article  >  Backend Development  >  Go code not printing posted json value from jquery ajax

Go code not printing posted json value from jquery ajax

WBOY
WBOYforward
2024-02-09 14:30:09808browse

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

php editor Xinyi shares a solution to help you avoid printing the json value published from jquery ajax in Go code. In this way, you can effectively control the printout and ensure the readability and safety of the code. Whether in front-end or back-end development, this technique is very practical and helps you better process json data. Let’s take a look at the specific implementation method!

Question content

Question details

go code not printing posted json value from jquery ajax

Go to code master

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 code

$.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>

Workaround

You are sending json data but postform uses url encoded data. You can do this:

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
}

The above is the detailed content of Go code not printing posted json value from jquery ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete