laravel 5简单的ajax从数据库检索记录

Jul*_*eto 3 php laravel laravel-5

如何使用Ajax检索数据?当我从数据库中检索记录时,我已经在一些项目中使用了我的ajax代码,但是由于它具有路由和控制器,所以不知道如何在laravel 5中创建它。

我有这个HTML

<select name="test" id="branchname">
    <option value="" disabled selected>Select first branch</option>
    <option value="1">branch1</option>
    <option value="2">branch2</option>
    <option value="3">branch3</option>
</select>

<select id="employees">
    <!-- where the return data will be put it -->
</select>
Run Code Online (Sandbox Code Playgroud)

和ajax

$("#branchname").change(function(){
    $.ajax({
        url: "employees",
        type: "post",
        data: { id : $(this).val() },
        success: function(data){
            $("#employees").html(data);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我声明了2个雄辩的模型,模型1用于分支名称表,模型2用于雇员表

use App\branchname;
use App\employees;
Run Code Online (Sandbox Code Playgroud)

所以我可以像这样检索数据(请参阅下文)

public function getemployee($branch_no){
    $employees = employees::where("branch_no", '=', $branch_no)->all();
    return $employees;
}
Run Code Online (Sandbox Code Playgroud)

如何返回我从employee表中提取的记录?从ajax首先与控制器通信并返回响应到ajax发布请求的路由进行布线?

任何帮助,建议,建议,想法,线索将不胜感激。谢谢!

PS:我是Laravel 5的新手。

The*_*pha 5

首先,在您的<head>部分中添加以下条目Master Layout

<meta name="csrf-token" content="{{ csrf_token() }}" />
Run Code Online (Sandbox Code Playgroud)

这将_token在您的视图中添加,以便您可以将其用于post and suchlike请求,然后还在JavaScript每个请求均加载的通用文件中为全局ajax设置添加以下代码:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
Run Code Online (Sandbox Code Playgroud)

因此,csrf_token对于需要this的方法,您不必担心或自己添加_token。现在,对于发布请求,您可以只使用通常的方式Ajax向您的Controllerusing 发送请求jQuery,例如:

var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
    // ...
});
Run Code Online (Sandbox Code Playgroud)

在这里,url应该与url您的雇员的路线声明相匹配,例如,如果您声明了这样的路线:

Route::post('employees/{branch_no}', 'EmployeeController@getemployee');
Run Code Online (Sandbox Code Playgroud)

然后,employeesurl和return json响应,以从中填充select元素Controller,因此下面给出了所需的代码(包括javaScript):

$.post('/employees/'+$(this).val(), function(response){
    if(response.success)
    {
        var branchName = $('#branchname').empty();
        $.each(response.employees, function(i, employee){
            $('<option/>', {
                value:employee.id,
                text:employee.title
            }).appendTo(branchName);
        })
    }
}, 'json');
Run Code Online (Sandbox Code Playgroud)

Controller您应该发送json_encoded数据,例如:

public function getemployee($branch_no){
    $employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
    return response()->json(['success' => true, 'employees' => $employees]);
}
Run Code Online (Sandbox Code Playgroud)

希望你有主意。