数据表服务器端处理分页问题 [英] Datatables server side processing pagination issue

查看:64
本文介绍了数据表服务器端处理分页问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使数据表与我的其余API一起很好地发挥作用.让我只说一下蝙蝠的权利:"REST api不会更改!.

I am trying to make datatables play well with my rest API. Let me just state right of the bat: "The REST api will not be changed!.

在使用服务器端处理时,数据表希望发送特定的查询参数,并希望返回特定的格式.对我来说,这是布洛克.没有人愿意修改他们的后端以匹配第三方库的约定(尽管我想,提供默认值很好.)

When using serverside processing, datatables wants to send specific query parameters and expects to get back a specific format. This, to me, is bullocks. Noone wants to modify their backend to match the convention of a third party library (although, I suppose, it is great that there is a default provided).

我已经这样设置了我的桌子:

I have set up my table like so:

{
    "processing": true,
    "serverSide": true,
    "ajax": {
      "url": "/api/customers/",
      "dataSrc": "results",
      "data": function (data, settings) {
        // Modify query parameters to match my API
        data.page = ...
        data.page_size = ...
        return data
      }
    },
    ...
}

您可以说,我使用了ajax.data属性来控制表从API请求的内容.这很棒.奇迹般有效.当响应返回时,看起来像这样

As you can tell, i have used the ajax.data property to govern what the table requests from the API. This is great. works like a charm. When the response returns, it looks like this

{
    "count": 85,
    "next": "http://myurl.com/?page=2",
    "previous": null,
    "results": [
        ...  // The actual data
    ]
}

从我的配置中,您可以说出我使用ajax.dataSrc来使表拾取results属性,但是我找不到任何有关如何从响应中拾取分页信息的文档.我尝试将配置修改为

From my configuration, you can tell that I use ajax.dataSrc to have the table pick up the results property, but I can't find any documentation regarding how to pick up pagination info from my response. I have tried modifying my configuration to

{
    ...
    "ajax": {
      "url": "/api/customers/",
      "dataSrc": function(data) {
          return {
              recordsTotal: data.count,
              recordsFiltered: ...,
              data: data.results,
              ...
          }
      },
      ...
    },
    ...
}

但是那只是抛出一个错误.似乎不可能...那么,那我该怎么办?

But that just threw an error. Does not seem to be possible... So then, what can I do?

推荐答案

您是正确的-使用ajax.dataSrc选项是不可能的.它告诉DataTables在哪里获取行数据(在您的示例中为data.results),但是无法使用ajax.dataSrc告诉它在哪里获取recordsTotal等.

You are correct - this isn't possible using the ajax.dataSrc option. It tells DataTables where to get the data for the rows (data.results in your example), but there is no way using ajax.dataSrc to tell it where to get the recordsTotal etc.

为此,您需要使用ajax选项作为函数-进行Ajax调用并返回一个对象.基本上与您已经在做的类似,但是您也调用$.ajax.

For that you need to use the ajax option as a function - make your Ajax call and return an object. Basically similar to what you are doing already, but you call $.ajax as well.

这篇关于数据表服务器端处理分页问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆