【问题标题】:laravel 5 simple ajax retrieve record from databaselaravel 5 简单的 ajax 从数据库中检索记录
【发布时间】:2015-07-21 03:46:19
【问题描述】:

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

在我的控制器中,我声明了 2 个 eloquent 模型,模型 1 用于分支名称表,模型 2 用于员工表

use App\branchname;
use App\employees;

这样我就可以检索数据(请参阅下文)

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

如何返回我从员工表中提取的记录?从 ajax 第一次与控制器通信并返回对 ajax 发布请求的响应的路由进行接线?

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

PS:我是 Laravel 5 的新手。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案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】:

      首先,在Master Layout&lt;head&gt; 部分添加以下条目:

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

      这将在您的视图中添加_token,以便您可以将它用于post and suchlike 请求,然后还在每个请求时加载的通用JavaScript 文件中添加以下全局ajax 设置代码:

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

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

      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 响应以从您的 select 元素填充 Controller,因此所需的代码(包括 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');
      

      您应该从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]);
      }
      

      希望你明白了。

      【讨论】:

      • 我按照您的指示操作,但它仍然给我“加载资源失败:服务器响应状态为 500(内部服务器错误)”
      • 错误说缺少“getemployee”的参数,我确定它是“$branch_no”参数。如何从 ajax 发布请求中获取发送的 id 并将其发送到 getemployee 控制器进行查询?
      • 糟糕!我的错误,更新了答案,检查$.post(url+'/'+$(this).val(), function(response){...});
      • 现在选择框填充了一个具有 NaN 文本的选项
      • $.each(response.employees, function(i, employee){...})里面试试employee.idemployee.title,我犯了一个错误:p
      【解决方案3】:

      添加您的路线:

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

      阿贾克斯:

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

      【讨论】:

      • 我使用@The Alpha 代码指南并整合您的路线,但它仍然返回我“juliver.laravel.com/employees500(内部服务器错误)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.(匿名函数)@jQuery-2.1.3.min.js:4(匿名函数) @ 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 juliver.laravel.com/employees 500 (内部服务器错误)|"
      • 错误说缺少“getemployee”的参数,我确定它是“$branch_no”参数。如何从 ajax 发布请求中获取发送的 id 并将其发送到 getemployee 控制器进行查询?
      猜你喜欢
      • 1970-01-01
      • 2016-01-31
      • 2020-09-21
      • 1970-01-01
      • 2012-04-15
      • 2020-08-08
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多