【问题标题】:jQuery Datatable is not a function when ajax reloadingajax重新加载时jQuery Datatable不是函数
【发布时间】:2018-01-31 22:07:48
【问题描述】:

我正在使用 .net 和 knockoutjs。我有一个通过 ajax 成功加载和填充数据的数据表。我看到的问题是当我尝试添加调用以使用更新的过滤器值重新加载数据时。当我调用其中包含 DataTable().ajax.reload() 的函数时,我收到错误“Uncaught TypeError: $(...).DataTable is not a function”

为什么表格加载成功,但以后对 DataTables 的任何调用都失败了?我以前做过类似的事情,但效果很好,所以不确定到底发生了什么。

在下面的代码中,如果您找到过滤器功能,您将看到我到底在哪里得到了错误。失败的不是 ajax.reload 调用本身,它只是试图通过 ID 获取表并对其执行 .DataTable()。

@{
    ViewBag.Title = "Classrooms";
}

<div class="container" id="classrooms-div">
    <h1>Classrooms</h1>

    <div class="row">
        <div class="col-md-2">
            <a class="btn btn-primary" href="@Url.Action("Create", "Classroom")"><i class="fa fa-plus-circle"></i> Add Classroom</a>
        </div>
    </div>
    <br />

    <div id="filters" style="border: 1px solid black; padding: 10px;border-radius: 5px;width:400px;margin-bottom:20px;">
        <div class="form-group row">
            <label for="district" class="col-sm-2 col-form-label">District</label>
            <div class="col-sm-10">
                <select class="form-control adminfield" id="district" data-bind="options: districts, optionsValue: 'id', optionsText: 'value', optionsCaption: 'Select a District', value: selectedDistrict"></select>
            </div>
        </div>

        <div class="form-group row">
            <label for="school" class="col-sm-2 col-form-label">School</label>
            <div class="col-sm-10">
                <select class="form-control adminfield" id="school" data-bind="options: schools, optionsValue: 'id', optionsText: 'value', optionsCaption: 'Select a School', value: selectedSchool"></select>
            </div>
        </div>

        <div class="form-group row">
            <label for="conditions" class="col-sm-2 col-form-label">Research Condition</label>
            <div class="col-sm-10">
                <select class="form-control adminfield" id="conditions" data-bind="options: conditions, optionsValue: 'id', optionsText: 'value', optionsCaption: 'Select a Research Condition', value: selectedCondition"></select>
            </div>
        </div>

        <button class="btn btn-primary" data-bind="click: filter">Filter</button>
    </div>

    <table class="table table-bordered table-hover" id="classrooms-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Grade</th>
                <th>District</th>
                <th>School</th>
                <th>Begin Date</th>
                <th>End Date</th>
                <th></th>
            </tr>
        </thead>
    </table>
</div>

<script type="text/javascript">
    var dashboardViewModel = function () {
        var self = this;
        self.classrooms = ko.observableArray();
        self.schools = ko.observableArray();
        self.districts = ko.observableArray();
        self.researchConditions = ko.observableArray();
        self.selectedSchool = ko.observable();
        self.selectedDistrict = ko.observable();
        self.selectedCondition = ko.observable();

        //when the district changes, update the schools
        self.selectedDistrict.subscribe(function (newValue) {
            if(newValue != undefined && newValue != "")
            {
                //load the schools for this district
                self.LoadSchoolsByDistrict(self.selectedDistrict());
            }
        });

        self.LoadSchoolsByDistrict = function (district) {
            showSpinner(true);
            $.ajax({
                url: '@Url.Action("LoadSchoolDropdownByDistrict", "School")',
                type: 'POST',
                data: { districtId: district },
                success: function (response) {
                    showSpinner(false);
                    if (response.Success == true) {
                        self.schools(response.Entity);
                    }
                    else {
                        console.log(response.Message);
                        toastr.error(response.Message);
                    }
                },
                error: function (response) {
                    showSpinner(false);
                    toastr.error("Error while loading schools!");
                    console.log(response.Message);
                }
            });
        };

        self.LoadDistricts= function () {
            showSpinner(true);
            $.ajax({
                url: '@Url.Action("LoadDistrictDropdown", "District")',
                type: 'POST',
                success: function (response) {
                    showSpinner(false);
                    if (response.Success == true) {
                        self.districts(response.Entity);
                    }
                    else {
                        console.log(response.Message);
                        toastr.error(response.Message);
                    }
                },
                error: function (response) {
                    showSpinner(false);
                    toastr.error("Error while loading districts!");
                    console.log(response.Message);
                }
            });
        };

        self.filter = function () {
            var table = $('#classrooms-table').DataTable(); //THIS LINE FAILS HERE
            table.ajax.reload();
        };

        self.loadInitialData = function () {
            $('#classrooms-table').DataTable({
                "processing": true,
                "serverSide": true,
                "order": [[0, "asc"]],
                "iDisplayLength": 10,
                "ajax": {
                    "url": '@Url.Action("LoadPagedClassrooms", "Classroom")',
                    "type": "POST",
                    "data": function (d, settings) {
                        d.district = self.selectedDistrict();
                        d.school = self.selectedSchool();
                        d.condition = self.selectedCondition();
                    }
                },
                "columns": [
                    {
                        "render": function (data, type, full, meta) {
                            var button1 = '<a title="Click to View Details" href="@Url.Action("Details","Classroom")/' + full.id + '?role=admin">' + full.name + '</a>';
                            return button1;
                        }, "sortable": true
                    },
                    { "data": "grade" },
                    { "data": "districtName" },
                    { "data": "schoolName" },
                    { "data": "beginDate" },
                    { "data": "endDate" },
                    {
                        "render": function (data, type, full, meta)
                        {
                            var button1 = '<a title="Details" href="@Url.Action("Details","Classroom")/' + full.id + '"><i class="fa fa-list"></i></a>';
                            var button2 = '<a title="Edit" href="@Url.Action("Edit", "Classroom")/' + full.id + '"><i class="fa fa-pencil-square-o"></i></a>';
                            var button3 = '<a title="Delete" href="@Url.Action("Delete", "Classroom")/' + full.id + '"><i class="fa fa-trash-o"></i></a>';
                            return button1 + " | " + button2 + " | " + button3;
                        }, "sortable": false, "width": "65px"
                    },
                ]
            });
        }
    };

    var dashboardVM = new dashboardViewModel();
    dashboardVM.loadInitialData();
    dashboardVM.LoadDistricts();
    ko.applyBindings(dashboardVM, $('#classrooms-div')[0]);
</script>

【问题讨论】:

  • 你试过:var table; self.loadInitialData = function () {table = $('#classrooms-table').DataTable({ //..so on然后table.DataTable(); //THIS LINE FAILS HERE?因此,您对数据表的初始实例化将保存到一个变量(在 init 和 filter 函数的范围内),然后您在 filter 函数中引用该变量。您可能需要移动您的过滤器函数,使其位于执行初始加载的函数下方。
  • 可能与 jQuery 有关。在不包括 jQuery 的情况下可以调用 self.filter 的任何机会吗?或者 jQuery 被包含两次,DataTables 有它自己的版本?还是在 jQuery 之前包含 DataTables?您可以尝试在var table = $('#classrooms-table').DataTable(); 之前添加$.noConflict();

标签: jquery ajax datatable datatables


【解决方案1】:

由于某种原因,您没有使用 var table = $('#classrooms-table').DataTable(); 获得原始 DataTables 对象的引用

Object 的原始 init 上的选项 retrieve 应使其返回原始实例:

self.loadInitialData = function () {
        $('#classrooms-table').DataTable({
            "retrieve": true,
            "processing": true,
            ...

【讨论】:

  • 我在数据表的初始初始化中添加了检索选项,但这还不足以使其正常工作。
【解决方案2】:

这就是我最终得到这个工作的方法。

    self.loadInitialData = function () {
        self.table = $('#classrooms-table').DataTable({
            "retrieve": true,
            "processing": true,
            "serverSide": true,
            "order": [[0, "asc"]],
            "iDisplayLength": 10,
            "ajax": {
                "url": '@Url.Action("LoadPagedClassrooms", "Classroom")',
                "type": "POST",
                "data": function (d, settings) {
                    d.district = self.selectedDistrict();
                    d.school = self.selectedSchool();
                    d.condition = self.selectedCondition();
                }
            },
            "columns": [
                {
                    "render": function (data, type, full, meta) {
                        var button1 = '<a title="Click to View Details" href="@Url.Action("Details","Classroom")/' + full.id + '?role=admin">' + full.name + '</a>';
                        return button1;
                    }, "sortable": true
                },
                { "data": "grade" },
                { "data": "districtName" },
                { "data": "schoolName" },
                { "data": "beginDate" },
                { "data": "endDate" },
                {
                    "render": function (data, type, full, meta) {
                        var button1 = '<a title="Details" href="@Url.Action("Details","Classroom")/' + full.id + '"><i class="fa fa-list"></i></a>';
                        var button2 = '<a title="Edit" href="@Url.Action("Edit", "Classroom")/' + full.id + '"><i class="fa fa-pencil-square-o"></i></a>';
                        var button3 = '<a title="Delete" href="@Url.Action("Delete", "Classroom")/' + full.id + '"><i class="fa fa-trash-o"></i></a>';
                        return button1 + " | " + button2 + " | " + button3;
                    }, "sortable": false, "width": "65px"
                },
            ]
        });
    };

    self.filter = function () {
        self.table.ajax.reload();
    };

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 2018-02-10
    • 2023-03-11
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多