我正在尝试将数据从 django 1.8.1 中的服务器加载到 jquery 数据表。在该过程结束时,我收到“未捕获的类型错误:无法读取未定义的属性‘长度’”javascript 错误。
查看;
datas = Datas.objects.all()
jsonData = serializers.serialize('json', datas)
return HttpResponse(jsonData, content_type='application/json')
在浏览器的“Network”中可以看到它返回这样的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
});
你能帮忙吗?谢谢
最佳答案
检查 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"
},
{...}
]
您可以迭代 View 中的数据来构建对象,将它们附加到数组中,然后通过 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)
关于javascript - Django jquery 数据表 : Uncaught TypeError: Cannot read property 'length' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30237637/