laravel 5 simple ajax从数据库中检索记录

时间:2015-05-10 16:59:48

标签: 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>

和ajax

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

在我的控制器中,我宣布了两个雄辩的模型,模型1用于branchname表,模型2用于员工表

use App\branchname;
use App\employees;

所以我可以检索数据(如下所示)

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

如何返回我从employees表中提取的记录?从ajax首先与控制器通信的路由连接并返回对ajax post请求的响应?

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

PS:我是Laravel 5的新手。

3 个答案:

答案 0 :(得分:4)

首先,在<head>的{​​{1}}部分添加以下条目:

Master Layout

这会在您的视图中添加<meta name="csrf-token" content="{{ csrf_token() }}" /> ,以便您可以将其用于_token个请求,然后在加载的公共post and suchlike文件中添加以下全局ajax设置代码每一个要求:

JavaScript

因此,对于需要此$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); 的方法,您无需担心或自行添加csrf_token。现在,对于帖子请求,您可以使用常规方式使用_tokenAjax发出Controller请求,例如:

jQuery

此处,var data = { id : $(this).val() }; $.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"}) // ... }); 应与员工的路线声明的url相匹配,例如,如果您已声明这样的路线:

url

然后,Route::post('employees/{branch_no}', 'EmployeeController@getemployee'); employees并返回url响应,以填充json中的select元素,因此需要此代码(包括javaScript)如下:

Controller

$.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'); 发送Controller数据,例如:

json_encoded

希望你明白了。

答案 1 :(得分:1)

首先检查ajax调用启动的页面的URL
example.com/page-using ajax

在AJAX中 如果您致电$.get('datalists', sendinput, function())
你实际上正在向GET请求 example.com/page-using ajax/datalists

在路线中 Route::get('page-using-ajax/datalists', xyzController@abc)

在控制器方法中

if (Request::ajax())
    {
        $text = \Request::input('textkey');
        $users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
        $users = json_encode($users);
        return $users;
    }

在Ajax成功函数中

function(data) {
    data = JSON.parse(data);
    var html = "";
    for (var i = 0; i < data.length; i++) {
        html = html + "<option value='" + data[i].city + "'>";
    };
    $("#datalist-result").html(html);
}

答案 2 :(得分:0)

添加您的路线:

Route::post('employees', [
    'as' => 'employees', 'uses' => 'YourController@YourMethod'
]);

的Ajax:

Change:
url: "employees"
to:
url: "/employees"