Django jquery datatable:Uncaught TypeError:无法读取属性' length'未定义的

时间:2015-05-14 12:39:41

标签: javascript jquery python django

我试图在django 1.8.1中从服务器向jquery数据表加载数据。在流程结束时,我得到了#34; 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 个答案:

答案 0 :(得分:1)

检查jQuery DataTables的doumentation: https://www.datatables.net/examples/ajax/objects.html

您需要按以下格式提供数据:


path: public_html/
url: http://example.dev
user: admin
core skip-plugins:
  - hello
core skip-themes:
  - twentyfifteen
  - twentyfourteen
  - twentythirteen
core download:
  locale: en_GB
core config:
    dbname: example
    dbuser: root
    dbpass:
    extra-php: |
        define( 'WP_DEBUG', true );
        define( 'WP_POST_REVISIONS', 10 );
core install:
    title: Example
    admin_user: admin
    admin_password: admin
    admin_email: admin@example.dev
plugin install:
  - wordpress-seo
  - wp-scss
  - wp-sync-db

您可以在视图中迭代数据以构建对象,将它们附加到数组,然后通过JsonResponse发送响应:

[
    {
    "name":    "Tiger Nixon",
    "position":   "System Architect",
    "salary":    "$3,120",
    "start_date": "2011/04/25",
    "office":    "Edinburgh",
    "extn":    "5421"
    },
    {...}
]

答案 1 :(得分:0)

查看;

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
        });

这是一个答案..