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

标签 javascript jquery python django serialization

这是问题的延续 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].modeldata.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/

相关文章:

python - Tensorflow 2.0 : custom keras metric caused tf. 函数回溯警告

python - csv.reader 在字段名称中返回 "OrderedDict"值

php - 如何在 php 中使用正则表达式从字符串中提取用户名

javascript - 地理围栏功能 - 放置 map 点、多边形、识别多边形内的点

javascript - 带有 jquery 对话框的 javascript 中的 session 超时警告

javascript - jQuery 帮助删除追加后的 div

python - 为每个查询打开一个新的 MySQL 游标是否很慢?

javascript - Ember.js 两个API的资源名称相同

javascript - 调用现有 JSFunction 时来自 WKWebView 的 WKErrorDomain 错误 4

jQuery UI Accordion : open multiple panels at once