尝试访问json数据时未定义(ajax)

时间:2016-06-07 22:15:07

标签: javascript jquery ajax django django-models

当我尝试访问django视图从ajax发送的数据时我得到了未定义

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}}]

警报消息: alert message

任何想法:D

2 个答案:

答案 0 :(得分:2)

循环中的

x是数组的索引,因此您需要:alert(data[x].model)

请参阅for..in loop

此外,如果您使用的是Django 1.7+,请使用JsonResponse

from django.http import JsonResponse

    ...

    else:
        objs = Tender.objects.all()[:4]
        return JsonResponse(objs)

答案 1 :(得分:0)

[ //<- 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...

OR

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