簡體   English   中英

無法從JS / jQuery中的序列化python對象獲取數據

[英]Can't get data out of serialized python object in JS/jQuery

這是服務器端Django視圖(restframework端點)的AJAX調用內部錯誤問題的繼續。 現在有一個前端問題。

$.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獲取某些信息時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].modeldata.notifications[1].pk或其他任何數據,例如data.notifications[1].fields.whom所有這些在理論上都必須正確無誤,但什么也不會返回。

TypeError: undefined is not an object (evaluating 'data.notifications.fields.choice_fl')

EDIT2:也嘗試過手動設置字段

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);

好吧,不知道出什么問題了,但這很好

$.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:

 nots = serializers.serialize('json', Notification.objects.all(), fields=('whom','choice_afl'))
data = {
    'notifications': nots

}
return Response(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM