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

时间:2021-12-14 01:38:10

How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.

如何使用ajax检索数据?我有一些我在我的一些项目中使用的ajax代码,当从数据库中检索记录但不知道如何在laravel 5中进行,因为它有路由和控制器。

I have this html

我有这个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>

and the ajax

和ajax

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

and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table

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

use App\branchname;
use App\employees;

so I could retrieve the data like (refer below)

所以我可以检索数据(参见下文)

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

how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?

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

any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!

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

PS: im a newbie in Laravel 5.

PS:我是Laravel 5的新手。

3 个解决方案

#1


At first, add following entry in your <head> section of your Master Layout:

首先,在主版面的部分添加以下条目:

<meta name="csrf-token" content="{{ csrf_token() }}" />

This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:

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

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

So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:

因此,对于需要此_token的方法,您无需担心或自己添加csrf_token。现在,对于post请求,您可以使用常规方法使用jQuery向Controller发出Ajax请求,例如:

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

Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:

在这里,url应匹配员工的路由声明的url,例如,如果您已声明这样的路由:

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

Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:

然后,employees是url并返回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');

From the Controller you should send json_encoded data, for example:

在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]);
}

Hope you got the idea.

希望你明白了。

#2


First check url of page from which ajax call initiates
example.com/page-using ajax

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

In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to example.com/page-using ajax/datalists

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

In Routes
Route::get('page-using-ajax/datalists', xyzController@abc)

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

In Controller Method

在控制器方法中

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

In Ajax Success Function

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

#3


Add in your route:

添加您的路线:

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

Ajax:

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

#1


At first, add following entry in your <head> section of your Master Layout:

首先,在主版面的部分添加以下条目:

<meta name="csrf-token" content="{{ csrf_token() }}" />

This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:

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

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

So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:

因此,对于需要此_token的方法,您无需担心或自己添加csrf_token。现在,对于post请求,您可以使用常规方法使用jQuery向Controller发出Ajax请求,例如:

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

Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:

在这里,url应匹配员工的路由声明的url,例如,如果您已声明这样的路由:

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

Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:

然后,employees是url并返回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');

From the Controller you should send json_encoded data, for example:

在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]);
}

Hope you got the idea.

希望你明白了。

#2


First check url of page from which ajax call initiates
example.com/page-using ajax

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

In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to example.com/page-using ajax/datalists

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

In Routes
Route::get('page-using-ajax/datalists', xyzController@abc)

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

In Controller Method

在控制器方法中

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

In Ajax Success Function

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

#3


Add in your route:

添加您的路线:

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

Ajax:

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