简体   繁体   English

排序或搜索时数据表中没有可用数据

[英]No data available in datatable when sort or searching

I have a datatable which is being populated after an ajax call when the page loads. 我有一个数据表,该页面在页面加载后会在ajax调用后填充。 The datatable is populated as expected, but when I click to sort or search, it shows a No data available message and all data previously populated is gone. 数据表已按预期填充,但是当我单击以进行排序或搜索时,它显示“无可用数据”消息,并且先前填充的所有数据都消失了。

I tried to populate it by creating the columns via jquery and via html and search/sort is not working both ways. 我试图通过jquery和html创建列来填充它,但是搜索/排序不能同时起作用。

 $(document).ready(function() { $.ajax({ url: "${pageContext.request.contextPath}/api/list", type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, error: function(response, textStatus) { if (response.status == "401") { location.href = "${pageContext.request.contextPath}/pages/login.jsp"; } else { alert("error"); } }, success: function(response, textStatus) { populateTable(response) } }); function populateTable(response) { $(function() { $("#dataTable tbody").html(""); $.each(response, function(i, item) { var body = "<tr>"; body+= "<td>" + item.name + "</td>"; body+= "<td>" + item.surname + "</td>"; body+= "</tr>"; $( "#dataTable tbody" ).append(body); }); }); $( "#dataTable" ).DataTable(); } }); 
 <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Surname</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> 

I expect to be able to sort and search without getting the No data available message 我希望能够排序和搜索而不会收到“无可用数据”消息

Sorting is not working because may be you are adding rows manually. 排序不起作用,因为您可能正在手动添加行。

By doing so you are not utilizing all features provided by Datatable. 这样一来,您将无法利用Datatable提供的所有功能。

Please try something like this, its more cleaner 请尝试这样,它更干净

$(document).ready(function() {
    $('#dataTable').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "${pageContext.request.contextPath}/api/list"
            "type": "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        },
        "columns": [
            { "data": "name " },
            { "data": "surname" }
        ]
    });
});

我已使用以下示例作为基础,并且现在可以正常工作

http://jsfidsdle.net/gh/get/jquery/2.2/chennighan/RapidlyPrototypeJavaScript/tree/master/lesson4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM