Laravel中的DataTable无法正常工作

时间:2017-12-24 16:56:07

标签: jquery laravel datatables

我试图在Laravel中实现DataTables,但它无法正常工作。表:

<table class="table table-striped" id="Clientes">
        <thead>
          <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Domicilio</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
</table>

剧本:

  $(document).ready(function() {
    $('#Clientes').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": '{{ route('getClientes') }}',
        "columns": [
          {"data": 'id', "name": 'id'},
          {"data": 'nombre', "name": 'nombre'},
          {"data": 'domicilio', "name": 'domicilio'}
        ]
    } );
} );

路线:

Route::get('/api/clientes', [
        'as'    => 'getClientes',
        'uses'  => function(){
        $clientes = Cliente::select(['id','nombre','domicilio'])->get();
        return Datatables::of($clientes)->make();}
    ]);

该表显示错误: DataTables警告:table id = Clientes - Ajax错误。有关此错误的详细信息,请参阅http://datatables.net/tn/7

但我无法解决问题。谁能帮忙吗?

UPDATE

错误是: 消息&#34;:&#34; Class&#39; Yajra \ Datatables \ Facades \ DataTables&#39;找不到&#34;, &#34; exception&#34;:&#34; Symfony \ Component \ Debug \ Exception \ FatalThrowableError&#34;,

2 个答案:

答案 0 :(得分:0)

最后不要使用get()

而不是

$clientes = Cliente::select(['id','nombre','domicilio'])->get();

使用

$clientes = Cliente::select(['id','nombre','domicilio']);

答案 1 :(得分:0)

数据表服务器端 查看

                                <table  class="table table-striped display nowrap" id="brand">
                                    <thead class=" text-primary">
                                    <th>
                                        ID
                                    </th>
                                    <th style="width: 85%">
                                        Brand
                                    </th>

                                    <th>
                                        Active
                                    </th>
                                    </thead>
                                    <tbody style="font-size: 12px; font-weight: bold">

                                
                                    </tbody>
                                </table>
<script>
$(document).ready(function() {
    $('#brand').DataTable( {
        dom: 'Bfrltip',
        pageLength: 10,
        lengthMenu: [ 5, 10, 20, 50, 100, 200, 500, 1000,2000,3000,4000, 50000, 100000],
        // processing:true,
        // serverSide:true,
        "oLanguage": {
            sLengthMenu: " Length of rows _MENU_ ",
        },

        ajax:{
            url:"{{ url('Main/fetch_brand') }}",
            dataType: "json",
            type:"POST",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // error:function()
            // {
            //     alert("Something went wrong. Please refresh the page.");
            //     location.reload();
            // }

        },

        order:[],

        buttons: [
            {
                extend:    'copyHtml5',
                text:      '<i class="fa fa-files-o"></i>',
                titleAttr: 'Copy',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }

            },
            {
                extend:    'excelHtml5',
                text:      '<i class="fa fa-file-excel"></i>',
                titleAttr: 'Excel',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }

            },

            {
                extend:    'csvHtml5',
                text:      '<i class="fa fa-file-csv"></i>',
                titleAttr: 'CSV',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }


            },
            {
                extend:    'pdfHtml5',
                text:      '<i class="fa fa-file-pdf"></i>',
                titleAttr: 'PDF',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }


            }
        ]
    } );
} );

</script>

控制器

    function brand(){
    if(session('role')){
    $obj = new  BackendModel;
    $data['data']=$obj->get_brand();

        return view('brand',$data);
    }else{
        return view('login');
    }
}
function fetch_brand(Request $request){

    $obj = new  BackendModel;
    $callData= $obj->call_brand();
    $totalData = count($obj->count_call_brand());
    $counter = 1;
    foreach ($callData as $row) {
        $callData = array();
        $callData[] = $counter;
        $callData[] = $row->name;
        $callData[] = '  <button type="button"  class="btn btn-sm btn-primary editfrom" data-id="{{ $row->id }}"  data-toggle="modal" data-target="#exampleModal1">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <span class="btn btn-sm  btn-danger"><i class="fas fa-trash"></i></span>';

        $data[] = $callData;
        $counter++;
    }
    $output = array(
        "draw"              =>  intval($request->input('draw')),
        "recordsTotal"      =>  intval($totalData),
        "recordsFiltered"   =>  intval($totalData),
        "data"              =>  $data
    );
    echo json_encode($output);


}

模型

   public function call_brand(){
        $calling = 0;
        $query = $this->get_data_brand($calling);

        return $query;
    }
    public function count_call_brand(){
        $calling = 1;
        $query = $this->get_data_brand($calling);

        return $query;
    }
    public function get_data_brand($calling){

        if(!empty($_POST["order"]))
        {
            DB::orderBy($_POST['order']['0']['column'], $_POST['order']['0']['dir']);
        }


        if($calling==1){
            if(isset($_POST["length"]) && $_POST["length"]  != -1)
            {
               DB::limit($_POST['length'], $_POST['start']);
            }
        }
        if(isset($_POST["search"]["value"]))
        {
            $fields  = Schema::getColumnListing('brand');

            foreach ($fields as $field)
            {
                if($field!="id" ){
                    DB::where($field, 'like', '%'.$field.'%');


                }

            }
        }


        $query = DB::table('brand')->get();



        return $query;

    }