【问题标题】:How to paginate a data table that is rendered via AJAX in Laravel?如何在 Laravel 中对通过 AJAX 呈现的数据表进行分页?
【发布时间】:2019-11-03 11:42:38
【问题描述】:

我正在尝试在 Laravel 中呈现一个 Blade 模板,该模板包含一个带有通过 AJAX 获得的数据的 HTML 表,并且需要使用 Laravel 的 LengthAwarePaginator 手动对结果进行分页。

我有一个名为 reports.blade.php 的主刀片文件,其中包含对名为 SalesController@get_sales_forecast 的控制器方法的 AJAX 调用。在该控制器中,我从 MSSQL 数据库中获取一些数据并呈现一个名为 sales-forecast-table 的局部视图,该视图将数据放入 HTML 表中。这一切都成功了。

但是,我现在尝试对这些结果进行分页,因为数据集非常大。

在我的主刀片文件 (reports.blade.php) 中,AJAX 调用如下所示:

$.ajax({
   type: 'POST',
   url:'{{action('SalesController@get_sales_forecast')}}',
   data: {
         _token: $('meta[name="_token"]').attr('content'),
         start_date: $('#txtStartDate').val(),
         end_date: $('#txtEndDate').val()
  },
  success:function(data) {
         $('#table-sales-forecast').html(data.html);
  }
});

此外,reports.blade.php 包含一个局部视图:

<div class="table-responsive" id="table-part-forecast-annual">
    @include('sales-forecast-table')
</div>

AJAX 调用发送到 SalesController@get_sales_forecast,如下所示:

public function get_sales_forecast(Request $request) {

        //Get data from Sales model
        $sales_forecast = Sales::getSalesForecast($start_date, $end_date);

        //Get current page
        $current_page = LengthAwarePaginator::resolveCurrentPage();

        //Create new collection
        $item_collection = collect($sales_forecast);

        //Define how many items to show per page
        $page_limit = 25;

        //Slice the collection to get the items to display in current page
        $current_page_items = $item_collection->slice(($current_page * $page_limit) - $page_limit, $page_limit)->all();

        //Create paginator 
        $paginated_items = new LengthAwarePaginator($current_page_items, count($item_collection), $page_limit);

        //Set URL path for generated links
        $paginated_items->withPath($request->url());

        //Render the view as an HTML string
        $html = view('sales-forecast-table')->with(['sales_forecast' => $paginated_items])->render();

        //Return the HTML 
        return response()->json(compact('html'));
    }

从 AJAX 调用 (sales-forecast-table.blade.php) 呈现的视图如下所示:

@if(isset($sales_forecast))
    {!!$sales_forecast->links()!!}
    <table class='table table-hover table-striped table-bordered'>
        @foreach($sales_forecast as $record)
            <tr>
                <td>{{$record->id}}</td>
                <td>{{$record->location}}</td>
                <td>{!!$record->customer!!}</td>
                <td>{!!$record->forecast!!}</td>
        @endforeach
    </table>
@endif

此时,表格确实呈现并且页面链接甚至出现了。该表仅按预期显示前 25 行(根据 $page_limit = 25 行)并选择了第 1 页,但是当我单击任何其他页面链接时,我只会收到“无消息”错误。错误消息是如此模糊,以至于我不太确定从这里去哪里。也许我在 Laravel 中以一种过于复杂的方式使用 AJAX?我试图尽可能地遵守框架的约定,但如果这样可以使这个问题变得更容易,我愿意尝试不同的方式。

【问题讨论】:

  • 您的$paginated_items 中呈现的链接是否设置为在点击时通过 ajax 加载?点击这些链接应该去哪里?
  • 我想这就是我被困的地方。通常,在我不使用 AJAX 获取数据的页面上,单击 Laravel 内置分页呈现的页面链接只会重新加载当前页面,但会显示下一组数据并将页码添加到 URL。例如,如果页面的地址是 www.example.com 并且用户单击“2”,则页面将重新加载为 www.example.com?page=2。如果页面的限制设置为 25,它将显示接下来的 25 行数据。
  • 我不确定如何设置页面链接,他们将在其中调用 SalesController@get_sales_forecast。我确信这很简单,但因为有很多层,我很难弄清楚如何去做。
  • @thisiskelvin 忘记@你了,这是我第一次在这里发问题,所以我有点菜鸟。 :)
  • 你为什么要分页两次?你在你的收藏上做一次,然后在 laravel 类上做一次。

标签: javascript php ajax laravel


【解决方案1】:

我假设getSalesForcast 是一个范围,所以它应该返回一个集合。我建议使用forPage。我不是 100% 确定您如何在请求中获取开始日期和结束参数,但考虑到这些值,这应该可以工作。另外,我假设您使用的是时间戳。

const $page_limit = 25;

public function get_sales_forecast(Request $request) {

    //Get current page
    $current_page = LengthAwarePaginator::resolveCurrentPage();

    //Get data from Sales model
    $sales_forecast = Sales::where('created_at','>',$request->input('start_date'))
                      ->where('created_at','<',$request->input('end_date'))
                      ->forPage($current_page,self::$page_limit)
                      ->get();

    //Create paginator 
    $LengthAwarePaginator = new LengthAwarePaginator($sales_forecast, $sales_forecast->count(), self::$page_limit);

    //Set URL path for generated links
    $paginated_items->withPath($LengthAwarePaginator->url($current_page));

    //Render the view as an HTML string
    $html = view('sales-forecast-table')->with(['sales_forecast' => $LengthAwarePaginator->items()])->render();

    //Return the HTML 
    return response()->json(compact('html'));
}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2021-06-14
    • 2015-09-24
    • 2023-03-21
    • 2013-07-15
    • 2015-09-23
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多