Laravel 5.5 - 从JSON对象阵列为DataTables创建列标题

时间:2017-10-31 18:23:53

标签: javascript php arrays json datatables

以下代码段非常适合显示带有静态列标题的结果集。有没有办法使用我现有的JSON数组为DataTables创建列标题?

[view.blade.php](HTML)

<div class="row">
    <div class="col-lg-6">
        <div class="card mb-3">
            <div class="card-header"><i class="fa fa-user"></i> Users</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-compact" width="100%" id="dataTable" cellspacing="0"></table>
                </div>
            </div>
        </div>
    </div>
</div>

[view.blade.php](Javascript)

<script type="text/javascript">
    $(document).ready(function() {
        $('#dataTable').DataTable( {
            "scrollX": true,
            "scrollY": '55vh',
            "scrollCollapse": true,
            "paging": false,
            dom: 'ft',
            "aaData": {!! collect($users)->toJson() !!},

            // Make this dynamic (Pull this from the Json above)
            "aoColumns": [
                { "sTitle": "Name",   "mData": "name" },
                { "sTitle": "Email",  "mData": "email" },
            ]

        } );
    } );
</script>

[从数据库返回的示例JSON对象/数组]

array:1 [
  0 => {#195
    +"id": 1
    +"name": "Josh_W"
    +"email": "user@email.com"
    +"group": "Admin"
    +"level": 5
    +"password": "PASSWORD"
    +"remember_token": null
    +"created_at": "2017-10-12 14:42:38"
    +"updated_at": "2017-10-12 14:42:38"
  }
]

2 个答案:

答案 0 :(得分:1)

看起来aoColumns只是一个对象数组,所以你应该能够遍历你的JSON来构建它。这样的事情可能是:

var json = {{ $json_var_from_controller }},
    aoColumns = [];

for(var key in json[0]) {
    aoColumns.push(
        {"sTitle": key[0].toUpperCase() +  key.slice(1), "mData": key }
    );
}

然后,在创建数据表时,请使用"aoColumns": aoColumns

答案 1 :(得分:1)

您可以尝试这样的事情(un-tested

@php ($userData = collect($users))
@php ($rowKeys = array_keys($userData->first(['name', 'email'])->toArray()))

<script type="text/javascript">
    $(document).ready(function()
    {    
        function ucwords(str) {
            return (str + '')
                .replace(/^(.)|\s+(.)/g, function ($1) {
                  return $1.toUpperCase()
                })
        }

        function getCols() {
            var rowKeys = {!! json_encode($rowKeys) !!}
            var results = [];
            for (var rowKey in rowKeys) {
                results.push({
                    sTitle: ucwords(rowKey.replace(/_/g, ' ')),
                    mData: rowKey
                });
            }
            return results;
        }

        $('#dataTable').DataTable( {
            "scrollX": true,
            "scrollY": '55vh',
            "scrollCollapse": true,
            "paging": false,
            dom: 'ft',
            "aaData": {!! $userData->toJson() !!},
            "aoColumns": getCols()
        } );

    } );
</script>

如果你想要json中的所有列,那么使用它:

@php ($rowKeys = array_keys($userData->first()->toArray()))