javascript 如何从jquery数据表中的ajax调用获取动态列标题和结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27482980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:32:20  来源:igfitidea点击:

how to get the dynamic column header and result from ajax call in jquery datatable

javascriptjqueryajaxdatatablejquery-datatables

提问by user3829086

I want to display the dynamic column header along with the results in datatable.In aaData and aoColumns attributes has to get result data and columns name from ajax call, Please suggest me how to do this or give me some alternate solution to get the dynamic data and column header from ajax call, Here is my code.:

我想与数据表中的结果一起显示动态列标题。在 aaData 和 aoColumns 属性中必须从 ajax 调用中获取结果数据和列名,请建议我如何执行此操作或给我一些替代解决方案来获取动态数据和来自 ajax 调用的列标题,这是我的代码。:

var $table=$('#MSRRes').dataTable( {
    "bFilter": false,                         
    "bDestroy": true,
    "bDeferRender": false,
    "bJQueryUI": true,
    "oTableTools": {
        "sSwfPath": "swf/copy_cvs_xls_pdf.swf",
    },
    "sDom": 'TC<"clear">l<"toolbar">frtip',
    "ajax" :{
        url: 'getResult.php',
        type: "POST",
        data: {
           formData:postData,
         }  
    },
    "aaData": results.DATA ,
    "aoColumns": [ column_names ]
});

Here is my ajax call to get the result data and column names to be display:

这是我的 ajax 调用,用于获取要显示的结果数据和列名:

$result=$afscpMsrMod->getAdvanceSearchResults($colCond,$whereCond,$having);
foreach($cols as $col) {
    array_push($colArr, $colnames);
}
$colJson= json_encode($colArr);
$newarray = array(
    "draw"            => 1,
    "recordsTotal"    => sizeof($result),
    "recordsFiltered" => sizeof($result),
    "data"            => $result,
    "COLUMNS"         => $colJson   
);
echo json_encode($newarray);

回答by ZenCodr

There doesn't seem to be a way to have dynamic column names using functionality within DataTables. You can work around this, if you do the ajax request yourself, (e.g. $.ajax) and then on the .complete of the ajax request, set the DataTable columns options appropriately using the ajax data you just got back, and then create the datatable. This also means that you can never simply reload your table data, but you will need to re-initialise the table each time data is requested.

似乎没有办法使用 DataTables 中的功能来获得动态列名。您可以解决这个问题,如果您自己执行 ajax 请求(例如 $.ajax),然后在 ajax 请求的 .complete 上,使用您刚刚返回的 ajax 数据适当地设置 DataTable 列选项,然后创建数据表。这也意味着您永远不能简单地重新加载表数据,但每次请求数据时都需要重新初始化表。

Steps:

脚步:

  1. Manually do an ajax request yourself
  2. Use that ajax data to construct the column object that you will pass to the DataTables columns option.
  3. Initialise your datatable using the column object you created in step 2, and using the data returned in step 1.
  1. 自己手动做一个ajax请求
  2. 使用该 ajax 数据来构造您将传递给 DataTables 列选项的列对象。
  3. 使用您在第 2 步中创建的列对象并使用第 1 步中返回的数据初始化您的数据表。

Note: The DataTable itself will not need to make any ajax requests, since you already have the data from step 1.

注意:DataTable 本身不需要发出任何 ajax 请求,因为您已经拥有步骤 1 中的数据。

EDIT: Here's an example using JQuery to make the ajax request:

编辑:这是一个使用 JQuery 发出 ajax 请求的示例:

// Assume this object is the json that the ajax request returns.
{
    customcols: ['lah', 'dee', 'dah'],
    mydata: [
        {
            lah: "value1",
            dee: "value2",
            dah: "value3",
        },
        {
            lah: "value4",
            dee: "value5",
            dah: "value6",
        },
        ]
}

Then, in response to something, something_happenedgets called.

然后,为了响应某事,something_happened被调用。

function something_happened(){
    $.ajax('/whatever/your/ajax/address/is')
        .done(maketable)
}

function maketable(data){
    var data = data.mydata;
    var column_names = data.customcols;
    var columns = []
    for (var i = 0; i < column_names.length; i++) {
        columns[i] = {
            'title': column_names[i],
            'data': column_names[i]
        }
    };
    $('#someplaceholder').DataTable({
        columns: columns,
        data: data,
    })

}

This example makes use of "Using an array of objects as a data source" (see http://datatables.net/reference/option/data).

此示例使用“使用对象数组作为数据源”(请参阅http://datatables.net/reference/option/data)。

回答by Viacheslav Avsenev

There is my example of it with ASP.NET MVC

这是我的 ASP.NET MVC 示例

Repo Method

回购方式

public List<Koef> GetColumnHeaders(int id)
{
    using (var _db = new DB_RiskiEntities())
        return _db.Koefs.Where(x => x.id_group == id).ToList();
}

Controller

控制器

[HttpPost]
public ActionResult GetColumnHeaders(int? id)
{
    return Json(
        _RiskiRepo.GetColumnHeaders(id ?? 0).Select(x => new { title = x.name })
        );
}

JS

JS

var Init = function () {
        $.ajax({
            url: "/Home/GetColumnHeaders",
            type: "POST",
            data: { id: group_id },
            success: function (result) {
                table = $('#tableid').DataTable({
                    "ajax": "/Home/GetMainDataAjax",
                    "columns": result,
                });

            }
        });
};

Using

使用

var FocusGroupChanged = function (_groupId) {
    group_id = _groupId;
    table.destroy();
    $('#tableid').empty();
    Init();
};

回答by Sandeep

I suggest the following approach. Ensure that the incoming JSON from AJAX request looks like

我建议采用以下方法。确保来自 AJAX 请求的传入 JSON 看起来像

{
    title: "Super Awesome AJAX DataTable",
    column_titles: [...],
    data: [[...], [...], [...], ...],
    ...
}

Now in the HTML/JS template use this snippet.

现在在 HTML/JS 模板中使用这个片段。

/* 
  params: JS Object containing GET parameters
  Optionally pass JSON URL source. 
*/
function updateTable(params) {
    $.getJSON(
        window.location.pathname,
        params,
        function(table) {
            // Set table title
            $('#title_box').text(table.title);

            // Set table headers
            var column_titles = table.column_titles.map(function(header) {
                return {
                    'title': header
                };
            });

            // Let datatables render the rest.
            $('#datatable').dataTable({
                "ordering": false,
                "searching": false,
                "paging": false,
                "info": false,
                "columns": column_titles,
                "data": table.data
            });
        }
    );
}

This technique can be easily extended to set table titles, footers, CSS classes etc.

这种技术可以很容易地扩展到设置表格标题、页脚、CSS 类等。