从客户端,我通过ajax post收到一些数据。数据类型是json格式。如何将请求数据转换为json或dict格式
function sendProjectBaseInfo() {
prj = {
id : $('#id').val(),
email : $('#email').val(),
title : $('#title').val(),
}
$.ajax({
url: '/prj/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: prj,
success: function(result) {
alert(result.Result)
}
});
}
得到json数据后,我尝试转换为json或dict格式。 转换为json。我这样写:
import json
def post(self, request):
if request.is_ajax():
if request.method == 'POST':
json_data = json.loads(request.data)
print('Raw Data : %s'%request.body)
return HttpResponse('OK!')
在上面的情况下,我得到500内部服务器错误。
所以我写下如下来解决这个错误。
import json
def post(self, request):
if request.is_ajax():
if request.method == 'POST':
data = json.dumps(request.data)
print('Raw Data : %s'%request.body)
return HttpResponse('OK!')
毕竟我得到了同样的错误。所以我正在研究所要求的数据。
import json
def post(self, request):
if request.is_ajax():
if request.method == 'POST':
print('Raw Data : %s'%request.body)
return HttpResponse('OK!')
打印出来是:
Raw Data : b'{"id":"1","email":"[email protected]","title":"TEST"}'
我怎样才能克服这种情况?
对我不起作用以下。 – eachone
@eachone:然后在这里打印完整的错误跟踪,否则我们将无法找出问题所在。 –
我在哪里可以得到错误信息?但是,我已经解决了这个错误。在客户端,数据:JSON.stringfy(prj)。您的评论对我有帮助。 – eachone