我的 JavaScript:
var postData = {
customer: 'test',
order: 1,
boxes: [
{
"size":"2",
"color":"1",
"colorNumber":"1",
"barCode":"1234567890",
"barCodePic":"",
},
{
"size":"3",
"color":"1",
"colorNumber":"2",
"barCode":"0987654321",
"barCodePic":"",
}
]
}
jQuery.post("http://10.0.1.7:8001/bapi/order/", postData );
我的Python:
print 'Customer:', request.POST.get('customer', None)
print 'Order:', request.POST.get('order', None)
print 'get - boxes:', request.POST.get('boxes', None)
print 'get - boxes[]:', request.POST.get('boxes[]', None)
print 'getlist - boxes[]:', request.POST.getlist('boxes[]')
print 'getlist - boxes:', request.POST.getlist('boxes')
print request.POST
输出:
Customer: test
Order: 1
get - boxes: None
get - boxes[]: None
getlist - boxes[]: []
getlist - boxes: []
<QueryDict: {u'customer': [u'test'], u'boxes[1][barCode]': [u'0987654321'], u'boxes[0][size]': [u'2'], u'boxes[1][colorNumber]': [u'2'], u'boxes[1][size]': [u'3'], u'boxes[0][colorNumber]': [u'1'], u'boxes[1][color]': [u'1'], u'boxes[0][barCode]': [u'1234567890'], u'boxes[1][barCodePic]': [u''], u'boxes[0][barCodePic]': [u''], u'boxes[0][color]': [u'1'], u'order': [u'1']}>
我所做的一切都没有让我得到我所期望的列表。我希望获得一个包含每个“盒子”对象的字典的 python 列表。
有人建议我使用“boxes[]”作为 JavaScript 中的参数名称,因此我的帖子数据将是:
var postData = {
customer: 'test',
order: 1,
'boxes[]': [
{
"size":"2",
"color":"1",
"colorNumber":"1",
"barCode":"1234567890",
"barCodePic":"",
},
{
"size":"3",
"color":"1",
"colorNumber":"2",
"barCode":"0987654321",
"barCodePic":"",
}
]
}
尝试时,输出是:
Customer: test
Order: 1
get - boxes: None
get - boxes[]: [object Object]
getlist - boxes[]: [u'[object Object]', u'[object Object]']
getlist - boxes: []
POST BELOW
<QueryDict: {u'customer': [u'test'], u'boxes[]': [u'[object Object]', u'[object Object]'], u'order': [u'1']}>
您可以在 QueryDict 中看到,这只是包含“[object Object”] 的 unicode 字符串列表。实际上不存在任何对象数据。
最佳答案
您需要首先对 JavaScript 对象进行编码。这些不能直接通过 GET 或 POST 参数传递。
在使用 jQuery POST
之前,尝试在 JavaScript 对象上调用 JSON.stringify() (即用 { "size":"3", "color ":"1"... }
)。例如:
[
JSON.stringify({
"size":"2",
"color":"1",
"colorNumber":"1",
"barCode":"1234567890",
"barCodePic":"",
}),
JSON.stringify({
"size":"3",
"color":"1",
"colorNumber":"2",
"barCode":"0987654321",
"barCodePic":"",
})
]
然后在Python中,使用类似的东西来解码它:
import json
box_0_string = request.POST.get('boxes[]')[0]
box_0_dict = json.loads(box_0_string)
获取各个 JSON 对象。
关于javascript - 无法检索从 jQuery 发布到 Django 的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131265/