Terrence
Terrence

Reputation: 116

Parameters of datatables'(https://datatables.net/) pagination not match with the server side

I'm trying to integrate datatables with an existing REST API, and got problem: The parameter names for pagination in datatables is start and length, but the name in rest api is page and size (API URL is something like /user?page=1&size=10), and I can't change the parameter names in the api. Is there a solution that can convert these two parameters?

Upvotes: 0

Views: 529

Answers (1)

You can use data table adapter to customize your request url.

function dataTableAdapter(sSource, aoData, fnCallback, oSettings) {

    var page, size;
    var serverDataConverter = function () { return { "0": "No data converter implemented" } };
    for (var i = 0; i < aoData.length; i++) {
        if (aoData[i].name == "iDisplayStart") {
            page= aoData[i].value;
        }
        else if (aoData[i].name == "iDisplayLength") {
            size= aoData[i].value;
        }
    else if (aoData[i].name == "sEcho") {
            echo = aoData[i].value;
        } 
    else if (aoData[i].name == "serverDataConverter") {
            // user provided function to convert the data coming back from the server.
            serverDataConverter = aoData[i].value;
        }     
    }

    var data=
     {
        page:page,
    size:size,
        // construct your request data here
     };


    $.ajax({
        url: sSource,
        type: "POST",
        data: data
    }).success(function (response) { dataTableCallback(response, fnCallback, serverDataConverter  echo ); });

}

function dataTableCallback(pageData, datatable_callback, serverDataConverter, echo ) {
    if (!pageData) return;

    var reply = new Object();
    reply.sEcho = echo;
    reply.iTotalRecords = pageData.TotalItems;
    reply.iTotalDisplayRecords = pageData.TotalFilteredItems;
    reply.aaData = new Array();

    if (pageData.Page) {
        for (var i = 0; i < pageData.Page.length; i++) {
           // You need to push your data in the right format here.
           reply.aaData.push(serverDataConverter(pageData.Page[i]));
        }
    }

    datatable_callback(reply);
}

And you can achieve this by calling datatable by

$('#id').DataTable({
   "fnServerData": dataTableAdapter,
   // other settings goes here
});

Upvotes: 1

Related Questions