无法从JS/jQuery中的序列化python对象中获取数据

2024-05-16 09:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

它是服务器端问题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);

      }
    }
  });

在控制台中获取以下错误:

^{pr2}$

在服务器端,一切都是正确的,我得到我需要的任何数据。我以为我需要先解析它,但当我试图解析时,它已经是一个对象了。否则,当我试图从对象TypeError: undefined is not an object中取出某些内容时。在

编辑:有一个打字错误,但问题仍然存在。如果我把它打印到控制台.log公司名称:

console.log(data.notifications);

什么都没有。但如果我警觉数据.通知:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

如果我更进一步,像我提到的data.notifications[1].model或{}或任何类似{}的东西,所有这些理论上都必须是正确的,但是没有返回任何东西。在

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"}, {

和之前一样,无论我进一步输入什么,它都是未定义的


Tags: logfieldsdatamodelobject服务器端notificationblog
2条回答

我不确定这是不是很好,但这是怎么回事

$.ajax({
    url: '/notify/',
    type:'GET',
    dataType: 'json',
    success: function (data) {

        alert(data['notifications']);
         var sed = JSON.parse(data['notifications'])
        alert(sed[2].fields.choice_afl);

    }
  });

在后端,如在EDIT2中:

^{pr2}$

你有个打字错误:

console.log(data.notifiications[1].fields);

应该是:

^{pr2}$

相关问题 更多 >