7

ネストされたオブジェクトを含む json オブジェクトをクライアントからサーバーに渡したいです。

クライアント側では、私のデータ構造は次のようになります。

var response = {};
response['screening'] = '1';
response['assistance'] = 'wheelchair access';
response['guests'] = {};
response['guests']['1'] = {}
response['guests']['1']['first'] = 'John'
response['guests']['1']['last'] = 'Smith'
response['guests']['2'] = {}
response['guests']['2']['first'] = 'Dave'
response['guests']['2']['last'] = 'Smith'

私のajax呼び出しは次のようになります:

$.ajax({
  type: "POST",
  url: window.location.pathname,
  data: response
 }).done(function( msg ) {
   alert( "Data Saved: " + msg );
 });

このデータを python フラスコを使用して実行されるサーバーに投稿した後、request.form オブジェクトを使用して、クライアントから投稿された内容を調べます。データを同じように構造化したいと思いますが、これはサーバー上の出力です。

ImmutableMultiDict([('guests[1][first]', u'John'), ('screening', u'2'), ('guests[2][last]', u'Smith'), ('guests[2][first]', u'Dave'), ('assistance', u'wheelchair access'), ('guests[1][last]', u'Smith')])

ご覧のとおり、response['guests'] オブジェクトはフラット化され、そのすべての子は次のようになります。

「ゲスト[2][最初]」

... は単なる文字列であり、親の応答 ['guests'] の要素ではありません。

このデータ ブロックをクライアントからサーバーに送信し、その構造を適切に維持するためのより良い方法はありますか?

ありがとう!

4

2 に答える 2

13

オブジェクトを JSON 文字列として送信できます。

var data = {
    screening: '1',
    assistance: 'wheelchair access',
    guests: [
        {
            first: 'John',
            last: 'Smith'
        },
        {
            first: 'Dave',
            last: 'Smith'
        }
    ]
};

$.ajax({
    type: 'POST',
    url: window.location.href,
    data: JSON.stringify(response),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
    alert("Data Saved: " + msg);
});

そして、 を使用request.jsonしてアクセスします。

于 2013-04-04T03:10:29.823 に答える
1

クライアント側では、その JavaScript オブジェクトを json 文字列に変換する必要があります。これを行うには、これを使用できます。

JSON.stringify(my_object) // This will return a string that you can pass in you ajax request

次に、サーバー側で、json モジュールを使用してそのオブジェクトを python 辞書に変換する必要があります。

import simplejson
my_new_object = simplejson.loads(my_json) // my_json is my_object from the client (previously called my_object)

my_new_object は python 辞書になりました。これでやりたいことは何でもできます

于 2013-04-04T15:28:40.127 に答える