当我试图从 ajax 访问由 django View 发送的数据时,我得到了未定义的信息
django View :
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 loop
此外,如果您使用的是 Django 1.7+,请使用 JsonResponse
from django.http import JsonResponse
...
else:
objs = Tender.objects.all()[:4]
return JsonResponse(objs)
关于javascript - 尝试访问 json 数据时未定义 (ajax),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37690298/