简体   繁体   中英

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. 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.

 $(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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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