2011-02-04 2 views
2

구조화 된 게시물 데이터와 함께 Ajax 요청을 보내고 있습니다.

$.post(
    myUrl, 
    { 
     items: [{code: 'a', description: 'aaa'}, 
       {code: 'b', description: 'bbb'}] 
    }) 

request.POST에 표시되는 내용은 다음과 같습니다.

<QueryDict: {u'items[0][code]': [u'a'], 
      u'items[0][description]': [u'aaa'], 
      u'items[1][description]': [u'bbb'], 
      u'items[1][code]': [u'b']}> 

원래 items를 얻기 위해 요청을 처리하려면 어떻게해야합니까?

(request.POST.get('items')은 작동하지 않습니다.)

답변

4

내가 요청을 통해 전송 구조화 된 데이터를 처리하기 위해 장고/파이썬 특별한 라이브러리를했다. GitHub here에서 찾을 수 있습니다.

+0

좋습니다! 그게 내가 필요한 것입니다. 이제 저는 다른 해결책을 채택했습니다. 그러나 앞으로 귀하를 사용할 것입니다. 감사. – Don

5

당신이 JSON과 같은 개체를 게시 좋을 것. Django에서는 JSON을 파이썬 객체로 구문 분석하여 구조를 다시 만들 수 있습니다.

포스트 JSON 장고보기에서

$.post(
    myUrl, 
    JSON.stringify({ 
     items: [{code: 'a', description: 'aaa'}, 
       {code: 'b', description: 'bbb'}] 
    }) 
) 

구문 분석 JSON jQuery를

와 함께

from django.http import HttpResponse 
from django.utils import simplejson 

def my_view(request): 
    if request.method == 'POST': 
     json_data = simplejson.loads(request.raw_post_data) 
     # json_data contains your objects 
     print json_data['items'] 

    return HttpResponse("Got data") 
+1

감사합니다. 나는 약간 다른 해결책을 채택했다 :'items : JSON.slugify (...)'를 보내고'simplejson.loads (request.POST [ 'items'])로 디코딩한다. – Don

+0

그래, +1, Don의 버전 (HTTP의 키/값 형식이 조금 더 적합). 그러나 아이디어는 같습니다. – Izkata

+0

Django 1.6에서 request.raw_post_data 대신 request.body를 사용하십시오. – elhoucine

관련 문제