客户端,我发送了一个JSON数据,包括像这样的列表类型数据。我怎样才能访问List类型的数据在django
$.ajax({
url: '/man/manual',
type: 'POST',
data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]},
dataType : 'JSON',
success : function(data) {
console.log(data);
}
});
我试图访问这些数据。
title = request.POST['title']
description = request.POST['description']
steps = request.POST['steps']
for step in steps:
print(step.title)
但我得到一个错误。
Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post
77. self.createManual(request)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual
27. steps = request.POST['steps']
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__
322. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /man/manual
Exception Value: "'steps'"
Request information:
GET: No GET data
POST:
description = 'desc'
steps[1][title] = '2'
steps[0][title] = '1'
title = 'ttt'
id = ''
如何将客户端的正确数据更改为代码。
我测试了你的建议,但是我收到了一条错误消息。异常值:JSON对象必须是str,而不是'bytes' 请求信息: GET:否GET数据 POST: {“id”:“111”,“title”:“ttt”,“description”: “desc”,“steps”:[{“title”:“1”},{“title”:“2”},{“title”:“3”}]} ='' – eachone
您是否使用过json。加载(request.body)'而不是'request.POST'在你的python代码中? – Foryah
json.loads(request.body.decode(),encoding ='utf-8')对我很有用 – eachone