如何对通过Laravel中的AJAX呈现的数据表进行分页?

时间:2019-06-20 15:44:54

标签: javascript php ajax laravel

我试图在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

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

1 个答案:

答案 0 :(得分:0)

我假设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'));
}