【发布时间】:2016-11-23 12:11:10
【问题描述】:
这是服务器端问题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],[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 中有错字?
-
@KevinKloet 抱歉,但我不明白那是什么问题
-
通知应该是通知
-
@Vinand 比较
data.notifications和data.notifiications -
在您的请求参数中将“dataType”参数设置为“json”
标签: javascript jquery python django serialization