donglu4633 2017-10-12 19:36
浏览 70
已采纳

Laravel 5.5 - 将MySQL查询传递给Javascript函数/ DataTables

I'd like to pass a SQL query to a Javascript function, found in my view, which will populate a HTML table using the DataTables API. I'm having trouble converting the object array into plain JSON. How would I go about doing so?

[web.php]

Route::get('/admin', function () {
    $users = DB::connection('mysql')->select('SELECT * FROM users');
    return view('admin', compact('users'));
});

[admin.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="userTable" cellspacing="0"></table>
                </div>
            </div>
        </div>
    </div>
</div>

[admin.blade.php] (Javascript)

<script type="text/javascript">
    $(document).ready(function() {
        $('#userTable').DataTable( {
            "scrollX": true,
            "scrollY": '55vh',
            "scrollCollapse": true,
            "paging": false,
            dom: 'ft',
            "aaData": "{{ $users }}",
            "aoColumns": [
                { "sTitle": "Name",   "mData": "name" },
                { "sTitle": "Email",  "mData": "email" },
            ]
        } );
    } );
</script>

[Example JSON object/array returned from database]

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"
  }
]
  • 写回答

1条回答 默认 最新

  • duanci1858 2017-10-12 19:41
    关注

    The select() method returns an array. You need to collect() the array and then call toJson():

    <script type="text/javascript">
        $(document).ready(function() {
            $('#userTable').DataTable( {
                "scrollX": true,
                "scrollY": '55vh',
                "scrollCollapse": true,
                "paging": false,
                dom: 'ft',
                "aaData": {!! collect($users)->toJson() !!},
                "aoColumns": [
                    { "sTitle": "Name",   "mData": "name" },
                    { "sTitle": "Email",  "mData": "email" },
                ]
            } );
        } );
    </script>
    

    To avoid escaping your JSON use the {!! !!} syntax.

    See the Laravel documentation on collections and displaying data on views for reference.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?