【问题标题】:Getting internal server error when trying to handle json in django尝试在 django 中处理 json 时出现内部服务器错误
【发布时间】:2013-05-15 11:45:55
【问题描述】:

我正在尝试接收从我的 jquery post 调用发送的 json 对象,如下面的代码所示。当

simplejson.loads(request.POST) 

被评论。但是,一旦我尝试对请求执行某些操作,我就会收到内部服务器错误 500。任何想法或任何其他方式来处理 json?

views.py

@csrf_exempt
def post_post(request):
print 'post_post'
if request.method == 'POST':
    print 'POST'
    messageData = simplejson.load(request.POST)
    return HttpResponse(simplejson.dumps("POST OK!"))
else:   
    return HttpResponse(simplejson.dumps("POST NOT OK!"))

projectViewModel.js

    var m = "Hello World";
        console.log(m);
        $.ajax({
        url: 'postNewPost/',
        type: 'POST',
        dataType: 'json',
        data: {client_response: JSON.stringify(m)},
         success: function(result) {
                    console.log(result);
                } 
        });

【问题讨论】:

  • 你的日志说是什么问题?
  • 在你的代码中你写的是simplejson.load而不是simplejson.loads。是不是打错字了?

标签: jquery python ajax django post


【解决方案1】:

这是因为您试图将字典传递给 loads() 方法。 request.POST 是一个带参数的字典。您可以使用request.raw_post_data 获取原始内容。

另外,simplejson 在 Django 中已被弃用,如果您使用的是 Python 2.6+,您应该只使用 Python json 包 (import json)

同样在您的 js 代码中,您传递参数 client_response 和其中的 json。在这种情况下,您只需将 request.POST['client_response'] 传递给 loads() 方法。但是更好的方法是直接传递json。

  data: JSON.stringify(m)

【讨论】:

    猜你喜欢
    • 2014-01-12
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多