2015-10-05 52 views
0

从客户端,我通过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"}' 

我怎样才能克服这种情况?

回答

0

您必须得到TypeError: the JSON object must be str, not 'bytes'例外。 (是Python3?)

如果是,那么 尝试在此之前json.loads.decode(encoding='UTF-8') 这是因为,响应主体是byte型的,如果在输出字符串的开头通知小b

if request.method == 'POST': 
     json_data = json.loads(request.body.decode(encoding='UTF-8')) 
     print('Raw Data : %s' % json_data) 
     return HttpResponse('OK!') 
+0

对我不起作用以下。 – eachone

+0

@eachone:然后在这里打印完整的错误跟踪,否则我们将无法找出问题所在。 –

+0

我在哪里可以得到错误信息?但是,我已经解决了这个错误。在客户端,数据:JSON.stringfy(prj)。您的评论对我有帮助。 – eachone

0

请求处理数据中的字节(数据类型)的形式所以首先我们需要将它转换成字符串格式,之后可以将其转换为json格式

import json 

def post(self,request): 
    if request.is_ajax(): 
    if request.method == 'POST': 
     json_data = json.loads(str(request.body, encoding='utf-8')) 
     print(json_data) 
    return HttpResponse('OK!') 
0
$.ajax({ 
    url: '/prj/', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    data: prj, #### YOUR ERROR IS HERE 
    success: function(result) { 
     alert(result.Result) 
    } 
}); 

您需要将您的数据转换成字符串在JS。

不要在你的js代码

data: JSON.stringify(prj) 
相关问题