2017-09-26 5 views
1

jQueryを使用して、そのプロパティの1つとして配列を持つJSONオブジェクトをAPIエンドポイントに送信しようとしています。jQueryは、そのプロパティの1つとして配列を含むJSONを正しくPOSTしません。

let bidding = { 
    "name": $("#name").val(), 
    "applicant": $("#applicant").val(), 
    "start_date": $("#start_date").val(), 
    "end_date": $("#end_date").val(), 
    "products": [] 
} 

$("#products").children(".dropdown").each(function(key, value) { 
    bidding.products.push(
    { 
    "product_name": $(value).children(".btn").text(), 
    "quantity": $(value).children("input").val() 
    } 
); 
}); 

そして、私はconsole.log(JSON.stringfy(bidding))を行うときに、それは例えば、期待と同じように解析します:私はこのようにそれを定義した

{ 
    "name":"Material de Construção", 
    "applicant":"Prefeitura", 
    "start_date":"26/09/2017", 
    "end_date":"01/10/2017", 
    "products":[ 
    {"product_name":"Cimento (5kg)","quantity":"200"}, 
    {"product_name":"Tijolo","quantity":"100"}, 
    {"product_name":"Caneta","quantity":"5"} 
    ] 
} 

しかし、私が投稿するときには、$.post("/api", bidding);私のAPIを使用すると、このようにそれを受け取ります:

{ 
    name: 'Material de Construção', 
    applicant: 'Prefeitura', 
    start_date: '26/09/2017', 
    end_date: '01/10/2017', 
    'products[0][product_name]': 'Cimento (5kg)', 
    'products[0][quantity]': '200', 
    'products[1][product_name]': 'Tijolo', 
    'products[1][quantity]': '100', 
    'products[2][product_name]': 'Caneta', 
    'products[2][quantity]': '5' 
} 

どのように私はそれがそうjQueryのは、アレイ内の各エントリのための新しいプロパティの作成を停止し、代わりに単一のプロパティとして配列全体を送信することができますか?

答えて

2

あなたはfalseに設定する必要があります。

processData:デフォルトでは、オブジェクトとしてデータオプションに渡されたデータは、(技術的には、文字列以外で)処理され、クエリ文字列に変換デフォルトのコンテンツタイプ「application/x-www-form-urlencoded」に適合します。 DOMDocumentやその他の未処理データを送信する場合は、このオプションをfalseに設定します。

したがって、あなたのポストは次のようになります。

$.ajax({ 
    type: "POST", 
    url: "/api", 
    data: JSON.stringify(bidding), 
    processData: false, 
    contentType: "application/json", 
    dataType:"json", 
    success: function() { 
    } 
}); 
+0

を維持するのは良い考えですので、私は先に行って、私の$ .post」/ API)を;」に置き換え"$ JAX({type:" POST "、url:"/api "、data:JSON.stringify(bidding)、processData:false、contentType:" application/json "、dataType:" json "、success:function (){}}); "そして、それはうまくいった。 –

1
$.post("/api", JSON.stringify(bidding)); 

とJSONをデコードし、サーバ側インチ「「(、入札あなたはJSONを使用したPHPの使用にjson_decode

を使用している場合は、常にオーケーデータ構造

+0

私はそれを試みましたが、BodyParserでExpress/Node.jsを使用していて、BodyParserが文字列を間違って解析していたので、あまりにも面倒でした。 –

関連する問題