簡體   English   中英

嘗試訪問json數據(ajax)時未定義

[英]undefined when trying to access json data (ajax)

當我嘗試從ajax訪問django視圖發送的數據時,我無法定義

django視圖:

def GetTenders(request):
print request.POST
if request.method == 'POST':
    print request.POST.get('Page')
    page_num = int(request.POST.get('Page'))
    if page_num != 1:
        start = (page_num - 1) * 4
        objs = Tender.objects.all()[start:(start + 4)]
        return HttpResponse(serializers.serialize('json', objs), content_type='application/json')
    else:
        objs = Tender.objects.all()[:4]
        print serializers.serialize('json', objs)
        return HttpResponse(serializers.serialize('json', objs), content_type='application/json')
else:
    print 'here'
    raise Http404

AJAX:

 $.ajax({type:"POST",url: "GetTenders",dataType: "json",
                            data: { "Page": $(this).text() },content_type:'application/json',
                            success:function (data) {
                            for(x in data){
                                alert(x.model);}}})

調試(在瀏覽器中響應):

[{"model": "Register.tender", "pk": 1, "fields": {"Name": "First", "Kind": "Public Trend", "Category": 1, "Description": "my first bid ", "Created_on": null, "Modified": null, "Active": true, "Size": "S", "Ministry": 1}}]

警報消息: 警報消息

任何想法:D

循環中的x是數組的索引,因此需要: alert(data[x].model)

for..in循環

另外,如果您使用的是Django 1.7+,請使用JsonResponse

from django.http import JsonResponse

    ...

    else:
        objs = Tender.objects.all()[:4]
        return JsonResponse(objs)
[ //<- Array 
    { //<- Object
        "model": "Register.tender",
        "pk": 1,
        "fields": { //<- Object
            "Name": "First",
            "Kind": "Public Trend",
            "Category": 1,
            "Description": "my first bid ",
            "Created_on": null,
            "Modified": null,
            "Active": true,
            "Size": "S",
            "Ministry": 1
        }
    }
]

訪問

var Obj = data[0];
Obj.model;
Obj.pk;
Obj.fields.Name
Obj.fields...

要么

data[x].model;
data[x].pk;
data[x].fields.Name
data[x].fields...

暫無
暫無

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

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