DataTable().ajax.reload() 未定义

DataTable().ajax.reload() not defined

我在DT v1.10下有如下代码:

var oTable = $('#items')
    .dataTable({
        sDom: "<'row'<'col-md-4'l><'col-md-6'f>r>t<'row'<'col-md-4'i><'col-md-7'p>>",
        oLanguage: {
            sLengthMenu: "_MENU_ per page"
        },
        ajax: "/items",
        bProcessing: true,
        bServerSide: true,
        aoColumnDefs: [
            {
                aTargets: [-1],
                bSearchable: false,
                bSortable: false
            }
        ]
    })
    .on('click', '.btn-danger', function (e) {
        if (confirm('Are you sure you want to delete SKU "' + $(this).data('sku') + '"?')) {
            $.getJSON($(this).attr('href'), function (data) {
                if ('success' in data) {
                    oTable.ajax.reload(null, false);
                }
            });
        }
        event.stopPropagation();
        return false;
    });

当服务器成功响应时,它会尝试调用行 oTable.ajax.reload(null, false); 但我总是收到错误 Uncaught TypeError: Cannot read property 'reload' of undefined

我做错了什么?

您使用的是旧版 API: $().dataTable()(v1.9 及更早版本),它在 DataTables v1.10 中仍然可用。旧的 API returns jQuery 对象,所以你应该使用 .api() 才能使用 DataTable API 方法:

oTable.api().ajax.reload();

新的 API 通过以下方式返回:$().DataTable()

Datatables FAQ

Q.: I get an error message stating that an API method is not available
A.: Very likely you are using a jQuery object rather than a DataTables API instance. The form $().dataTable() will return a jQuery object, while $().DataTable() returns a DataTables API instance. Please see the API documentation for further information.

API documentation

It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQueryJS object. An api() method is added to the jQuery object so you can easily access the API, but the jQuery object can be useful for manipulating the table node, as you would with any other jQuery instance (such as using addClass(), etc.).

作为 phillip100 回答的后续,您不必更改所有旧代码,或更改初始化方法即可使用新的 API。您始终可以即时获取数据表 1.10.x API :

...
if ('success' in data) {
  //oTable.ajax.reload(null, false);
  $('#items').DataTable().ajax.reload(null, false);
}
...

也很好。 jQuery dataTables 检查是否已经存在 $("#items") 的 dataTables 实例,因此不会有冗余。