【问题标题】:Dictionary inside dictionary from AJAX to Django从 AJAX 到 Django 的字典内字典
【发布时间】:2016-04-04 10:27:44
【问题描述】:

我的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 django python-2.7 django-models django-1.8


    【解决方案1】:

    在发送您的数据之前,请尝试发送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 版本是 request.raw_post_data 而不是 request.body

    【讨论】:

    • 这部分有效,因为我确实以该形式获取数据,但在后端我必须执行 json.loads(request.GET.keys()[0]) 才能获取该数据,这看起来像对我来说是个坏黑客:D,有没有更好的方法?
    • @dnit13 - 尝试做一个data = json.loads(request.body) 然后尝试data['emotions']['guilt']
    • @dnit13 - 如果这不能满足您的要求,那么我想这个library 会对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2015-11-28
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多