我传入的 Django 请求中的 JSON 数据在哪里? [英] Where's my JSON data in my incoming Django request?

查看:35
本文介绍了我传入的 Django 请求中的 JSON 数据在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Django/Python 处理传入的 JSON/Ajax 请求.

I'm trying to process incoming JSON/Ajax requests with Django/Python.

request.is_ajax() 在请求中是 True,但我不知道 JSON 数据的有效负载在哪里.

request.is_ajax() is True on the request, but I have no idea where the payload is with the JSON data.

request.POST.dir 包含:

['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
 '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', 
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 
'urlencode', 'values']

请求发布密钥中显然没有密钥.

There are apparently no keys in the request post keys.

当我查看 Firebug 中的 POST 时,有 JSON 数据被发送到请求.

When I look at the POST in Firebug, there is JSON data being sent up in the request.

推荐答案

如果您要将 JSON 发布到 Django,我想您需要 request.body (request.raw_post_data在 Django <1.4 上).这将为您提供通过帖子发送的原始 JSON 数据.从那里您可以进一步处理它.

If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.

这是一个使用 JavaScript、jQuery、jquery-json 和 Django 的示例.

Here is an example using JavaScript, jQuery, jquery-json and Django.

JavaScript:

JavaScript:

var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
               allDay: calEvent.allDay };
$.ajax({
    url: '/event/save-json/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: $.toJSON(myEvent),
    dataType: 'text',
    success: function(result) {
        alert(result.Result);
    }
});

姜戈:

def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.body   
    return HttpResponse("OK")

姜戈<1.4:

  def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.raw_post_data
    return HttpResponse("OK")

这篇关于我传入的 Django 请求中的 JSON 数据在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆