从数据库中获取记录的简单ajax方法:使用Laravel 5

3

如何使用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);
        }
    });
});

在我的控制器中,我声明了两个Eloquent模型。模型1用于branchname表,模型2用于employees表。

use App\branchname;
use App\employees;

所以我可以像以下这样检索数据。
public function getemployee($branch_no){
    $employees = employees::where("branch_no", '=', $branch_no)->all();
    return $employees;
}

如何返回我从员工表中提取的记录?从路由连线到控制器并将响应返回给ajax post请求?任何帮助、建议、推荐、想法、线索都将不胜感激。谢谢!

PS:我是Laravel 5的新手。

3个回答

5
首先,在您的“主布局”Master Layout<head>部分中添加以下条目:
<meta name="csrf-token" content="{{ csrf_token() }}" />

这将在您的视图中添加_token,以便您可以将其用于post和类似的请求。然后,在每个请求上加载的公共JavaScript文件中添加以下代码以进行全局ajax设置:

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

因此,您不需要为那些需要 _token 的方法担心或添加 csrf_token。现在,对于一个 post 请求,您可以使用通常的方式使用 jQuery 发送 Ajax 请求到您的 Controller,例如:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
    // ...
});

在这里,url应该与你的员工路由声明中的url匹配,例如,如果你声明了这样一个路由:

Route::post('employees/{branch_no}', 'EmployeeController@getemployee');

然后,employeesurl 并返回 json 响应以填充您的 Controller 中的 select 元素,因此该代码(包括 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');

控制器发送json_encoded数据,例如:

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

希望您已经了解了这个想法。

我按照您的指示操作,但仍然出现“无法加载资源:服务器响应状态为500(内部服务器错误)”的错误提示。 - Juliver Galleto
错误提示缺少“getemployee”的参数,我确定是“$branch_no”参数。我该如何从Ajax POST请求中获取发送的ID并将其发送到getemployee控制器进行查询? - Juliver Galleto
糟糕!我的错误,已更新答案,请检查 $.post(url+'/'+$(this).val(), function(response){...}); - The Alpha
现在选择框中填充了一个文本为NaN的选项。 - Juliver Galleto
尝试在 $.each(response.employees, function(i, employee){...}) 中使用 employee.idemployee.title,我犯了一个错误 :p - The Alpha

1

首先检查发起ajax调用的页面的url
example.com/page-using ajax

在AJAX中
如果你调用$.get('datalists', sendinput, function())
实际上是在向example.com/page-using ajax/datalists发出GET请求

在路由中
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);
}

0

在你的路由中添加:

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

Ajax:

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

我使用了@The Alpha代码指南并集成了你的路由,但仍然返回“http://juliver.laravel.com/employees 500 (Internal Server Error)n.ajaxTransport.k.cors.a.crossDomain.send @ jQuery-2.1.3.min.js:4n.extend.ajax @ jQuery-2.1.3.min.js:4n.each.n.(anonymous function) @ jQuery-2.1.3.min.js:4(anonymous function) @ main.js:60n.event.dispatch @ jQuery-2.1.3.min.js:3n.event.add.r.handle @ jQuery-2.1.3.min.js:3 jQuery-2.1.3.min.js:4 POST http://juliver.laravel.com/employees 500 (Internal Server Error)|"。 - Juliver Galleto
错误提示缺少“getemployee”的参数,我确定是“$branch_no”参数。我该如何从Ajax POST请求中获取发送的ID并将其发送到getemployee控制器进行查询? - Juliver Galleto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接