简体   繁体   English

无法从Laravel中的javascript调用控制器内部的函数

[英]Cannot call the function inside a controller from the javascript in laravel

I am trying to use datatables of jquery to create a table with fetched members from database. 我正在尝试使用jquery的数据表创建具有从数据库中提取的成员的表。 This is my html and javascript code: 这是我的html和javascript代码:

<table id="workerTable" class="table-bordered table-hover" width="80%" cellspacing="0">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Role</th>
                <th>Dep_id</th>
                <th>Start_Date</th>
                <th>Updated</th>
            </tr>
        </thead>
    </table>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#workerTable').DataTable( {
                "processing": true,
                "serverSide": true,
                "ajax": {{ URL::route('workerData') }}
            } );
        } );
    </script> 

I have this route defined: 我定义了以下路线:

Route::get('/workers/data' , 'WorkersController@fetch')->name('workerData');

And the function fetch() inside the WorkersController is like that: 而且WorkersController内部的函数fetch()就像这样:

public function fetch()
    {
        $workers = Worker::all();
        echo json_encode($workers);
    }

I am new to laravel and I think I am not understanding it well. 我是laravel的新手,我认为我不太了解。 Is the call to this line 是这条线的电话吗

"ajax": {{ URL::route('workerData') }} “ ajax”:{{URL :: route('workerData')}}

make the route to call the fetch function of the WorkersController ? 使路由调用WorkersController的fetch函数?

You should use this package if you're not already using it: https://github.com/yajra/laravel-datatables 如果尚未使用此软件包,则应该使用它: https : //github.com/yajra/laravel-datatables

Then replace 然后更换
"ajax": {{ URL::route('workerData') }}
by 通过
"ajax": {{ route('workerData') }}

And here's the correction for your function 这是您功能的更正

use App\Worker;
use Yajra\Datatables\Datatables;

// ...

public function fetch()
{
    $workers = Worker::all();

    return Datatables::of($workers)->make(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM