如何通过Laravel中的jquery Datatable检索和显示数据?

时间:2016-08-30 04:01:54

标签: php jquery datatable datatables laravel-5.2

基本上我的目的是从数据库中获取数据并使用laravel 5.2中的数据API进行显示。但是,我一直收到此错误/通知DataTables warning: table id=payments-table - Ajax error. For more information about this error,,请参阅http://datatables.net/tn/7

请注意,我按照此处的指示设置了我的开发环境:https://github.com/yajra/laravel-datatables(适用于Laravel 4 | 5的jQuery DataTables API)

我的表名是payments

这是我的路线代码:

Route::controller('payments', 'admin\paymentsController', [
            'anyData'  => 'payments.data',
            'getIndex' => 'datatables',
        ]);

然后管理文件夹中的控制器代码:

<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use Yajra\Datatables\Datatables;

class paymentsController extends Controller
{
    /**
     * Displays datatables front end view
     *
     * @return \Illuminate\View\View
     */
    public function getIndex()
    {
        return view('admin.payments', compact('payments'));
    }

    /**
     * Process datatables ajax request.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function anyData()
    {

        return Datatables::of(payments::query())->make(true);

    }
}

最后我在admin文件夹中的视图:

@extends('layouts.master')

@section('content')
    <table class="table table-bordered" id="payments-table">
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Amount</th>
        </tr>
        </thead>
    </table>
@stop

@push('scripts')
<script>
    $(function() {
        $('#payments-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{!! route('payments.data') !!}',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'amount', name: 'amount' },
                 ]
        });
    });
</script>
@endpush

请帮帮我哪里出错。感谢。

2 个答案:

答案 0 :(得分:1)

哦(叹气)终于,我解决了我的烂摊子。

为了那些想要知道如何在我的控制器课程中的人 我改变了return Datatables::of(payments::query())->make(true);

return Datatables::of(DB::table('payments'))->make(true);

我不太确定,但我认为起初我无法从数据库中获取数据。

所以我的控制器类变为:

<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use Yajra\Datatables\Datatables;

class paymentsController extends Controller
{
    /**
     * Displays datatables front end view
     *
     * @return \Illuminate\View\View
     */
    public function getIndex()
    {
        return view('admin.payments', compact('payments'));
    }

    /**
     * Process datatables ajax request.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function anyData()
    {


        return Datatables::of(DB::table('payments'))->make(true);
    }
}

一切都还在。 谢谢。

答案 1 :(得分:0)

试试这个例子:

JS:

$('#user_role_table').dataTable({
            "sServerMethod": "GET",
            //"bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "{{url('/getusers')}}",
            "aoColumns": [ { "bSortable": true }, { "bSortable": false }, { "bSortable": true }, { "bSortable": false }],
        });

控制器功能:

public function getusers()
    {
        $start  = $_REQUEST['iDisplayStart'];
        $length = $_REQUEST['iDisplayLength'];
        $sSearch = $_REQUEST['sSearch'];

        $col = $_REQUEST['iSortCol_0'];

        $arr = array(0 => 't1.name', 2 => 't3.name');

        $sortBy = $arr[$col];
        $sortType = $_REQUEST['sSortDir_0'];

        $getRoles = "select t1.id, t1.name as user_name, t1.email, t3.id as role_id, t3.name as role FROM users t1 JOIN role_user t2 ON t1.id = t2.user_id JOIN roles t3 on t2.role_id = t3.id where t1.status = '1' ".$userFilter.$condition." ORDER BY ".$sortBy." ".$sortType." LIMIT ".$start.", ".$length;

        $getRoles = DB::select(DB::raw($getRoles));

        // Get all data into an array
        foreach($getRoles as $result)
        {
            $data[] = (array)$result;
        }

        $iTotal = 0;

        $getUserRoleCount   = "select id from roles";
        $userRoleCount      = DB::select(DB::raw($getUserRoleCount));
        $iTotal             = count($userRoleCount);

        $rec = array(
            'iTotalRecords' => $iTotal,
            'iTotalDisplayRecords' => $iTotal,
            'aaData' => array()
        );

        $k=0;
        if (isset($data) && is_array($data)) {

            foreach ($data as $item) {
                $rec['aaData'][$k] = array(
                    0 => ucwords(strtolower($item['user_name'])),
                    1 => $item['email'],
                    2 => ucwords(strtolower($item['role'])),
                    3 => '<button id="'.$item['id'].'" name="'.$item['user_name'].'" email="'.$item['email'].'" role="'.$item['role_id'].'" class="btn btn-xs btn-info edit_user" href="javascript:void(0);"><i class="fa fa-edit"></i>User</button>'.'&nbsp;&nbsp;'.'<button id="'.$item['id'].'" role="'.$item['role_id'].'" class="btn btn-xs btn-info edit_permission" href="javascript:void(0);"><i class="fa fa-edit"></i>Permission</button>'
                );
                $k++;
            }
        }

        echo json_encode($rec);
    }

我使用的是相同的,并且工作正常。