繁体   English   中英

无法使用django-ajax从python返回JSON对象

[英]Can't return JSON object from python using django-ajax

尝试将此ajax插件应用于django https://github.com/yceruto/django-ajax我成功使用了ajaxPost,但是无法应用ajaxGet

在views.py中。 在python中,所有数据都可以正常打印。

    @ajax
    def notify(request):
     notifications = Notification.objects.filter(whom=request.user.profile)
     for acd in notifications:
        print(acd)
        print(acd.choice_afl)
        print(acd.whom)
        print(acd.who_did)
     return {'notifications': notifications}

在html中:

    $('.notifications_button').click(function(){

    ajaxGet('/notify/', function(notifications){

         for(var acd in notifications){

             alert(acd.choice_afl)
            $('#the_very_nw').html(acd.choice_afl);

         }
})

如果我提醒noty我得到的"notifications" ,如果我提醒acd.choice_afl我得到undefined (如果插入到HTML或根本不值一提),尽管蟒蛇我得到刺痛的结果,我需要。 怎么了? python对象不会转换为JSON对象吗?

编辑:同样为了安全,我将django对象序列化为json这样。 没有变化

data = serializers.serialize("json",notifications)
return {'notifications': data}

EDIT2:我看了JSON的结构

 var jsonPretty = JSON.stringify(JSON.parse(data),null,2); 
$('#the_very_nw').html(jsonPretty);

看起来像这样 所以我错过了“田野”,但是它什么都没有改变。 仍然没有打印任何内容。 这是万一我返回HttpResponse的情况:

[ { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 1 }, { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 2 }, { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 3 }, { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 4 }, { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 5 }, { "fields": { "how_much_new_notifications": 0, "number_of_new_notifications": 0, "who_did": 2, "question_answered_object": null, "whom": 1, "choice_afl": "F" }, "model": "blog.notification", "pk": 6 } ]

我认为错误出在您的JS代码中。 尝试如下重写循环:

for (var i = 0; i < notifications.length; i++) {
   var acd = notifications[i];
   $('#the_very_nw').html(acd.choice_afl);
}

目前acd只是数组的indeces,而不是它的元素(一个很好的解释在这里 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM