Ajax request for server side data for each page in

2019-07-11 03:14发布

问题:

I am using Jquery Datatables to load an array of array of data (aaData) obtained via ajax call from server side. I don't want to pull whole of the data at once rather I need to make ajax request for loading data every time user clicks "prev" or "next" in Datatables pagination.

How can this be achieved ?I want to make an ajax call and fetch results on the fly for that page only.

Below is the javascript code where in I am making a call.

$.ajax({              
 type: "GET",
 url: "ajaxBacklog",
 contentType: 'application/json',
 data: null,
 dataType: 'json',
 success: function(json){                  
     oTable = $("#backlogTable").dataTable({
         "aaData": json.aaData,
         "bProcessing": true,
         "bServerSide": true,
         "sPaginationType": "full_numbers",
         "bJQueryUI": true,
         "bRetrieve": true,
         "bPaginate": true,
         "bStateSave": true,
         "bSort": true,
         "aaSorting": [[ 4, "desc" ]],
         "iDisplayLength": 25,
         "oLanguage": {
                 "sProcessing": "<img src='resources/images/loader.gif'/>",
                 "sEmptyTable": "No records found."
             },
         "aoColumns": [
             { "sClass": "alignCenter"},
             { "sClass": "left"},
             { "sClass": "left"},
             { "sClass": "left"},
             { "sType": 'date-uk', "sClass":"datecolumn"},
             { "sType": 'date-uk', "sClass":"datecolumn"},
             { "sClass": "left"},
             { "sClass": "left"}
         ],
         "error": function() {
             alert("Failed to load Data");
         }
     });
    }
   }
);

I have also followed the server side processing of datatables as well but nothing is working.

回答1:

In datatables server-side processing every click on 'prev'/'next' button (also filter, sorting etc) call request (out of the box) to function specified in sAjaxSource property - you can check this call in your browser console.

Call have lot of usefull parameters. You need to use iDisplayLength and iDisplayStart in your function for cut (after sort and filter) your set of data from iDisplayStart to iDisplayStart+iDisplayLength.

You should of course change your code structure as you can see in datatables documentation - define datatables initialization code and indicate ajax source in sAjaxSource property.