Jquery Django:重建通过$.post发送的结构化参数
我正在发送一个带有结构化post数据的Ajax请求(使用jQuery):Jquery Django:重建通过$.post发送的结构化参数,jquery,ajax,django,post,Jquery,Ajax,Django,Post,我正在发送一个带有结构化post数据的Ajax请求(使用jQuery): $.post( myUrl, { items: [{code: 'a', description: 'aaa'}, {code: 'b', description: 'bbb'}] }) 我在request.POST中看到的是: <QueryDict: {u'items[0][code]': [u'a'], u'it
$.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']}>
我如何处理请求以获取原始项目
(请注意,
request.POST.get('items')
不起作用)我建议您将对象作为JSON发布。在Django中,您可以通过将JSON解析为python对象来重新创建结构
使用jQuery发布JSON
$.post(
myUrl,
JSON.stringify({
items: [{code: 'a', description: 'aaa'},
{code: 'b', description: 'bbb'}]
})
)
在Django视图中解析JSON
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")
我为Django/Python创建了一个特殊的库来处理通过请求发送的结构化数据。您可以在GitHub上找到它。您可以尝试:
request.POST.getlist('items')
谢谢我采用了一个稍微不同的解决方案:发送
items:JSON.slugify(…)
并使用simplejson.loads(request.POST['items'))进行解码(request.POST['items'))
Yeah,+1,虽然我倾向于使用@Don的版本(更适合HTTP的键/值格式),但想法是一样的。从Django 1.6开始,使用request.body而不是request.raw\u POST\u data.Good!这正是我需要的。现在,我采用了另一种解决方案,但将来我将使用您的解决方案。谢谢