Windsooon
Windsooon

Reputation: 7140

How to set next page url using jQuery DataTable

My server return data schema like this:

{
    "count": 161,
    "next": "http://127.0.0.1:8000/api/example/?page=3",
    "previous": "http://127.0.0.1:8000/api/example/?page=1",
    "results": [
        {
            "name": "foo",
            "version": "bar",
        }
    ]
}

And I using DataTable like this:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "/api/example/?page=1"
    } );
} );

How can I change the data source from url:

"next": "http://127.0.0.1:8000/api/example/?page=3",

When I click DataTable next or previous button.How to custom the parameter (page here) to let DataTable know?

From the example here Object data source the schema like this:

{
  "draw": 3,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    {
      "first_name": "Airi",
      "last_name": "Satou",
      "position": "Accountant",
      "office": "Tokyo",
      "start_date": "28th Nov 08",
      "salary": "$162,700"
    },
  ]
}

Each time I click the next button, the "draw" parameter will return the current page number.Should I have to add this to my server response? Or I should custom the onclick event on "next" or "previous" button, using ajax to get data then redraw the table? I also look at the plugin here Pagination plug-ins, Should I use it?

Upvotes: 3

Views: 5169

Answers (1)

Windsooon
Windsooon

Reputation: 7140

This work, you can set limit and offset to handle this.

$(document).ready(function() {
        $('#pirate_table').DataTable( {
            "processing": true,
            "serverSide": true,
            "bPaginate": true,
            "ajax": function(data, callback, settings) {
                    $.get('/api/example/', {
                        limit: data.length,
                        offset: data.start,
                        }, function(res) {
                            callback({
                                recordsTotal: res.count,
                                recordsFiltered: res.count,
                                data: res.results
                            });
                        });
            },
            "columns": [
                { "data": "name" },
                { "data": "version" }
            ]
        } );
    });

Upvotes: 4

Related Questions