duanluanhui8348 2015-05-10 16:59
浏览 54
已采纳

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

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.

I have this 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

$("#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

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?

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

PS: im a newbie in Laravel 5.

  • 写回答

3条回答 默认 最新

  • dqy27359 2015-05-10 18:30
    关注

    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:

    $.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:

    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:

    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:

    $.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:

    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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分