2016-08-10 8 views
0

jQueryを使用してWebアプリケーションで作業していますが、JSON形式について混乱しています。サーバーの場合、私はrestful Json Serverを使用しています。Typicode Json Serverで動作するコンポジットJsonオブジェクトの作成方法

問題は、何が問題なのかわかりません。エラーは、私がサーバーにポストするJson形式(Ajaxを使ったHTTP POST)が間違っているようです。私はこのステップを一歩一歩説明しようとします。

http://localhost:3000/dbで)JSONサーバの初期状況は次のとおりです。

{ 
    "userRecipes": [] 
} 

さて、次のように私はJSONオブジェクトを作成します。

var example2json = { 
    "description":"some desc", 
    "trigger":{ 
     "triggerType":"exampleType", 
     "field1":"something1", 
     "field2":"something2", 
     "field3":"something3" 
    } 
}; 

をそして、この架空のオブジェクトを3回送信しますサーバ:

これ以降、Jsonサーバーのステータスres最終的には:

{ 
    "userRecipes": [ 
    { 
     "description": "some desc", 
     "trigger[triggerType]": "exampleType", 
     "trigger[field1]": "something1", 
     "trigger[field2]": "something2", 
     "trigger[field3]": "something3", 
     "id": 1 
    }, 
    { 
     "description": "some desc", 
     "trigger[triggerType]": "exampleType", 
     "trigger[field1]": "something1", 
     "trigger[field2]": "something2", 
     "trigger[field3]": "something3", 
     "id": 2 
    }, 
    { 
     "description": "some desc", 
     "trigger[triggerType]": "exampleType", 
     "trigger[field1]": "something1", 
     "trigger[field2]": "something2", 
     "trigger[field3]": "something3", 
     "id": 3 
    } 
    ] 
} 

なぜJson形式が変更されるのですか?私は私がしなければならないのフィールドにアクセスするとき:

console.log(JSON.stringify(response.data.userRecipes[1]["trigger[triggerType]"])); 

が、私はこの方法でそれを行うだろう:

console.log(JSON.stringify(response.data.userRecipes[1].trigger.triggerType)); 

私はどこか間違って行くようにしてくださいんだけど、どこかわかりません。

唯一の疑いがあるのは、Json(配列の要素にネストされたオブジェクト)を間違って作成することです。または、このJson Serverについてわからないことがあります。

+0

AJAX POSTで 'data:JSON.stringify(example2json)'も使用しようとしましたが、そこにJson Serverがあります。これは文字通り '{ " {\ "description \":\ "some desc \" 「フィールド1」:\「フィールド1」:\「フィールド2」:\「フィールド2」:フィールド2:フィールド3: \ "something3 \"}} ":" "、 " id ":4 }です。 – kitsune

答えて

0

問題を解決しました。

contentType: 'application/json; charset=UTF-8', 

ので、これから:それに

$.ajax({ 
    method: "post", 
    url: "http://localhost:3000/userRecipes", 
    data: example2json, 
    dataType: "json", 
    success: function(response) { 
     $('#recipedDescriptionModal').modal('hide'); 
     url = "#SuccessRepice"; 
     window.location.replace(url); 

    } 
}); 

:POSTコンテンツの種類を指定する必要がありました私の場合は

$.ajax({ 
    method: "post", 
    url: "http://localhost:3000/userRecipes", 
    data: example2json, 
    contentType: 'application/json; charset=UTF-8', //This is the money shot ✅ 
    success: function(response) { 
     $('#recipedDescriptionModal').modal('hide'); 
     url = "#SuccessRepice"; 
     window.location.replace(url); 

    } 
}); 

、私は2つのフィールドを混乱しましたdataTypecontentType

dataTypeフィールドは応答のデータ形式を指定するために使用されます。

contentType要求のデータ形式を指定するために使用されます。

関連する問題