Django jquery 数据表:未捕获的类型错误:无法读取未定义的属性“长度”
2015-05-14
821
我尝试从 django 1.8.1 中的服务器将数据加载到 jquery 数据表。在过程结束时,我收到“Uncaught TypeError:无法读取未定义的属性‘length’”javascript 错误。
查看;
datas = Datas.objects.all()
jsonData = serializers.serialize('json', datas)
return HttpResponse(jsonData, content_type='application/json')
在浏览器的“网络”中可以看到它返回这样的 json 数组;
[{"fields": {"objectname": "O1"}, "model": "my_app.datas", "pk": 1}]
Html;
<table class="table table-striped table-bordered table-hover" id="id_dataTable" style="cursor: pointer;">
</table>
Js;
$('#id_dataTable').dataTable({
"sAjaxSource": '/getData/',
"aoColumns": [
{'mData': 'fields.objectname'}
],
"aoColumnDefs": [
{
"aTargets": [0],
"sTitle": "Object",
"sClass": "align-center"
}
],
"bProcessing": true,
"bServerSide": true,
"bPaginate": false
});
你能帮忙吗?谢谢
2个回答
查看 jQuery DataTables 的文档: https://www.datatables.net/examples/ajax/objects.html
您需要提供以下格式的数据:
[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{...}
]
您可以在视图中迭代数据以构建对象,将它们附加到数组,然后通过 JsonResponse 发送响应:
from django.http import JsonResponse
datas = Datas.objects.all()
arr = []
for data in datas:
arr.append({
'key1': data.key1,
'key1': data.key1,
})
return JsonResponse(arr, safe=True)
cbergmiller
2015-05-14
查看;
datas= Datas.objects.all()
dataArray = []
for store in datas:
dataArray.append({
'objectname':data.objectname
})
return JsonResponse({'data':dataArray}, safe=True)
Js;
$('#id_dataTable').dataTable({
"sAjaxSource": '/getData/',
"aoColumns": [
{'mData': 'objectname'}
],
"aoColumnDefs": [
{
"aTargets": [0],
"sTitle": "Object",
"sClass": "align-center"
}
],
"bProcessing": true,
"sAjaxDataProp": "data",
"bServerSide": true,
"bPaginate": false
});
这是一个答案..
kbrk
2015-05-14