过滤DataTable的AJAX响应

时间:2019-04-17 19:04:23

标签: javascript jquery json ajax datatables

我有一个DataTable函数。 parentObjData来自其他地方,应对此DataTable进行过滤,以仅包含idea_id等于parentObjData的记录。

function BuildExampleDataTable(parentObjData, tableCounter) {
    oInnerTable = $("#example_" + tableCounter).DataTable({
        autoWidth: true,
        serverSide: true,
        processing: true,
        ajax:
        {
            url: "/platform/api/?format=datatables",
            type: "get",
            data: function (d) {
                var searchData =
                    {
                        idea_id: parentObjData,
                        draw: d.draw,
                        length: d.length,
                        start: d.start,
                        order: d.order,
                        columns: d.columns,
                        orderbyfield: d.columns[d.order[0].column].data
                    };
                d.sData = JSON.stringify(searchData);
                return d.sData;
            }
        },
        columns: [
           { data: 'idea_id', name: "idea_id.id"},
           { data: 'comment' },
        ],
    });
}

/platform/api/?format=datatables回应:

{"data":[{"idea_id":1,"comment":"test comment"},{"idea_id":1,"comment":"test comment again"},{"idea_id":2,"comment":"another test comment?"}],"recordsFiltered":3,"recordsTotal":3,"draw":1}

parentObjData正确到达函数,但未过滤DataTable(它显示所有三个记录)。如何更改data调用的ajax部分以过滤DataTable?

1 个答案:

答案 0 :(得分:-1)

这是我的代码,您可以遵循它

"ajax": {
        "url": contextRoot + "manage/callbackMessage/datatables",
        "data": function (d) {
            var req = {
                "dir": "",
                "colName": "",
                "draw": d.draw,
                "length": d.length,
                "start": d.start
            };
            var queryReq = {
                "idea_id": parentObjData
            };

            var columns = d.columns;
            var order = d.order;
            if (order.length > 0) {
                var orderFirst = order[0];
                var colIndex = orderFirst.column;
                req.dir = orderFirst.dir;
                req.colName = columns[colIndex].name || columns[colIndex].data;
            }
            return $.extend({}, req, queryReq);
        }
    }

在服务器代码上,您可以根据需要解析dir colName drawidea_id

https://datatables.net/reference/option/ajax.data的更多详细信息