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 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿