从 AJAX 到 Django 的字典内字典

Dictionary inside dictionary from AJAX to Django

我的javascript代码是这样的:

var emotions = {};


$('#emotions').children('#emotionFields').each(function(){
        emotions[$(this).find($('.emotion')).val()]=$(this).find($('.value')).val()
    });

$.ajax({
            url: '../data',
            dataType: 'json',
            type: 'GET',
            data: {action: 'dosomething',word:word,emotions:emotions},
            success:function(response){
            //something  
            },
            error:function(msg){
                   //somethin
            }
});

所以就在 ajax 调用之前,我的情绪对象看起来像这样:

emotions: Object
excitement: "value1"
guilt: "value2"

当我从 djangos 读取这些数据时 request.GET 我看到了

{u'action': u'dosomething',
 u'emotions[excitement]': u'value1',
 u'emotions[guilt]': u'value2',
 u'word': u'word'}

现在,我如何将它转换成一个合适的字典,以便我可以访问兴奋和内疚?

在发送你的数据之前尝试做一个JSON.stringify()

...
$.ajax({
    ...
    contentType : "application/json",
    data : JSON.stringify({action: 'dosomething',word:word,emotions:emotions}),
    ...
...

然后在您的 Django 视图中:

...
data = json.loads(request.body)
print data['emotions']['guilt']
...

如果上面的代码不能满足你的要求,那么你可以使用这个library

编辑: 如果 Django 版本 <1.6,则使用 request.raw_post_data 而不是 request.body