django中的querydict对象_Django:从QueryDict读取JSON对象数组

How do I pass a composite JSON structure via AJAX call from JS and on the server side, read it as a "very similar" data structure in python?

I understand that json formatting can be used (simplejson etc), but I somehow feel that the QueryDict itself is malformed or reformatted in my case?

Example:

When passing an array of JSON objects [{"id": 1},{"id": 2},{"id": 3}] via AJAX to Django view, the QueryDict gets formatted as:

POST:

u'csrfmiddlewaretoken': [u'69bb3c434ced31ab301ede04bf491ec0'],

u'json_data[1][id]': [u'2'], u'json_data[2][id]': [u'3']}>

How do I even iterate through the json_data?

I want to get something like this instead:

POST:

u'csrfmiddlewaretoken': [u'69bb3c434ced31ab301ede04bf491ec0'], u'type': [u'clone']>

So that I can access QueryDict as a dictionary and retrieve json_data as a list and process it in a certain order: maybe just iterate through them in sequential list order.

Something like:

ret = request.POST

for item in ret['json_data']:

process(item['id'])

In fact the value that goes into process() could be another dictionary of key value pairs instead of just a number (1,2,3 etc)

Javascript:

var test = [{"id": 1},{"id": 2},{"id": 3}];

$.post(

"/insert_tc",

{

json_data: test,

"type": 'clone',

"csrfmiddlewaretoken": $csrf_token

},

function(json) {

//CALLBACK

},

"json"

);

views.py:

def insert_tc(request):

if request.method == 'POST':

ret = request.POST

type = ret['type']

list = ret.getlist(ret)

But list returns empty []

I tried simplejson dumps, loads, items, get methods but none of them helped.

I even tried jQuery.param( obj, true ), but that's not what I want (although somewhat close).

Is there a different/better way to pass composite data structures back and forth Django JS via AJAX?

解决方案

You should stringify your JSON using JSON.stringify(). This will convert the JSON Object into string format so it can be parsed correctly on the other end. On the other end you will need to use json.loads() to "unstringify" the object.

javascript:

var test = [{"id": 1},{"id": 2},{"id": 3}];

$.post(

"/insert_tc",

{

json_data: JSON.stringify(test),

"type": 'clone',

"csrfmiddlewaretoken": $csrf_token

},

function(json) {

//CALLBACK

},

"json"

);

View:

import json

def insert_tc(request):

if request.method == 'POST':

ret = request.POST

type = ret['type']

list = json.loads(ret['json_data'])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值