这是问题的延续 Internal error on AJAX call to a Django view (restframework endpoint)这是服务器端。现在前端出现问题。
$.ajax({
url: '/notify/',
type:'GET',
dataType: '',
success: function (data) {
if (data.notifications) {
console.log(data.notifiications[1].fields);
}
}
});
在控制台中出现以下错误:
TypeError: undefined is not an object (evaluating 'data.notifications')
在服务器端一切都是正确的,我得到了我需要的任何数据。我认为我需要先解析它,但是当我尝试解析时,它已经是一个对象了。否则,当我试图从对象中获取某些内容时,TypeError: undefined is not an object
。
编辑:有一个拼写错误,但问题仍然存在。如果我将其打印到 console.log:
console.log(data.notifications);
什么都没有。但是如果我警告 data.notifications: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] ,[对象对象]
如果我像我提到的那样更进一步,例如 data.notifications[1].model
或 data.notifications[1].pk
或其他类似 data.notifications[1].fields.whom
所有这些理论上都必须正确,但不返回任何内容。
TypeError: undefined is not an object (evaluating 'data.notifications.fields.choice_fl')
编辑2: 还尝试手动设置字段
nots = serializers.serialize('json', Notification.objects.all(), fields=('whom','choice_afl'))
data = {
'notifications': nots
}
return Response(data)
如果警报alert(data['notifications']);
得到这个:
[{"pk": 1, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 2, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 3, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 4, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 5, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 6, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {
和之前一样,无论我进一步输入什么,它都是未定义的
最佳答案
您有一个拼写错误:
console.log(data.notifiications[1].fields);
应该是:
console.log(data.notifications[1].fields);
关于javascript - 无法从 JS/jQuery 中的序列化 python 对象中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764225/