2017-01-19 1 views
0

GOLを使用してGolangを使用してWebアプリケーションを作成しています。 AjaxタイプがGETのときにjsonデータを持ち込むことができますが、AjaxタイプがPOSTのときは、jsonデータをGOサーバーに送信する方法はありません。私は方法PostForm()GetPostForm()を使用しましたが、動作しません。 Plzは私を助けます。GOLを使用してGolang製サーバーにJSONデータを持ち込みたい

join.js

 var json_memberInfo = `{ 
      "id": "`+id+`", 
      "password": "`+password+`", 
      "name": "`+name+`", 
      "birthday": "`+birthday+`", 
      "tel": "`+tel+`", 
      "email": "`+email+`" 
     }`; 

     var parse_memberInfo = JSON.parse(json_memberInfo); 

     alert(json_memberInfo); 

     $.ajax({ 
      url: "/join", 
      type: "POST", 
      data: parse_memberInfo, 
      contentType: "application/json", 
      success: function(result) { 
       if (result) { 
        //alert("회원가입이 완료되었습니다!"); 
       } 

       else { 
        //alert("에러가 발생하였습니다. 잠시 후에 다시 시도하여 주세요."); 
       } 
      } 
     }) 

main.go

router.POST("/join", func(c *gin.Context) { 
     id := c.PostForm("id") 
     password := c.PostForm("password") 
     name := c.PostForm("name") 
     birthday := c.PostForm("birthday") 
     tel := c.PostForm("tel") 
     email := c.PostForm("email") 

     fmt.Println(id + " " + password + " " + name + " " + birthday + " " + tel + " " + email) 
    }) 
+0

使用contentTypeのアプリケーション/の代わりにアプリケーション/ JSON – foecum

+1

のx-www-form-urlencodedで!どうもありがとうございました!!私はあなたが私の質問に答えるべきだと思う:) – Diana

答えて

1

サーバがapplication/x-www-form-urlencodedで期待するコンテンツの種類フォームを送信:

は、ここに私のコードです。ファイルをアップロードするためのがinutタイプ=「ファイルは、」コンテンツタイプはを可能にするフォームデータウィッヒとして渡されるサーバー/バックエンドがデータを識別できるようになるapplication/x-www-form-urlencodedapplication/jsonからコンテンツタイプを変更するmultipart/form-data

する必要があります使用されている場合c.PostFormを使用してフィールドを取得します。

link to the w3.org spec for forms

0

私はgin.Context.PostForm()機能がapplication/x-www-form-url-encodedデータにアクセスするためのものであると信じています。 application/jsonデータを受け入れるには、要求内の値をバインドするためにgin.Context.BindJSON関数を使用できます。これは、jsonまたはform-url-encodedのいずれかのデータを扱うことができます(下の例では、構造体にはjsonを処理するための注釈があります)。このため例の抜粋です:@foecum WOW ...それは働いている

type Member struct { 
    Id   string  `json:"id"` 
    Password string  `json:"password"` 
    Name  string  `json:"name"` 
    Birthday string  `json:"birthday"` 
    Tel   string  `json:"tel"` 
    Email  string  `json:"email"` 
} 

// various code 

router.POST("/join", func(c *gin.Context) { 
    var jsonData Member 
    if c.BindJSON(&jsonData) == nil { 
    fmt.Println(jsonData.Id + " " + jsonData.Password + " " + jsonData.Name + " " + 
     jsonData.Birthday + " " + jsonData.Tel + " " + jsonData.Email) 
    } else { 
    // handle error 
    } 
} 
関連する問題