[英]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. 我试图将数据表与现有的REST API集成,但出现问题:数据表中分页的参数名称为
start
和length
,而rest api中的名称为page
和size
(API URL类似于/user?page=1&size=10
),并且我无法在api中更改参数名称。 Is there a solution that can convert these two parameters? 有没有可以转换这两个参数的解决方案?
You can use data table adapter to customize your request url. 您可以使用数据表适配器来自定义请求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 您可以通过调用datatable通过
$('#id').DataTable({
"fnServerData": dataTableAdapter,
// other settings goes here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.