简体   繁体   English

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

[英]How to paginate a data table that is rendered via AJAX in Laravel?

I am trying to render a Blade template in Laravel that contains an HTML table with data obtained via AJAX, and need to manually paginate the results using Laravel's LengthAwarePaginator. 我试图在Laravel中渲染一个Blade模板,该模板包含一个包含通过AJAX获得的数据的HTML表,并且需要使用Laravel的LengthAwarePaginator手动对结果进行分页。

I have a main blade file called reports.blade.php which contains an AJAX call to a controller method called SalesController@get_sales_forecast . 我有一个名为reports.blade.php主叶片文件,其中包含一个AJAX调用名为SalesController @ get_sales_forecast控制器方法。 Within that controller, I am fetching some data from a MSSQL database and rendering a partial view called sales-forecast-table that puts the data in an HTML table. 在该控制器内,我正在从MSSQL数据库中获取一些数据,并渲染一个称为sales-forecast-table的局部视图,该视图将数据放入HTML表中。 That is all working successfully. 一切都成功进行。

However, I am now trying to paginate those results because the data set is very large. 但是,由于数据集非常大,我现在尝试对这些结果进行分页。

In my main blade file (reports.blade.php), the AJAX call looks like this: 在我的主刀片文件(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);
  }
});

Furthermore, reports.blade.php includes a partial view: 此外,reports.blade.php包含部分视图:

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

The AJAX call goes out to SalesController@get_sales_forecast, which looks like this: 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'));
    }

And the view being rendered from the AJAX call ( sales-forecast-table.blade.php ) looks like this: 从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

At this point, the table does render and the page links even appear. 此时,表格会渲染,甚至页面链接也会出现。 The table only displays the first 25 rows as expected (per the $page_limit = 25 line) with page 1 selected, but when I click on any of the other page links, I simply receive a "No message" error. 该表仅按预期显示前25行(每$page_limit = 25行),并选择了第1页,但是当我单击其他任何页面链接时,我只会收到“无消息”错误。 The error message is so vague that I'm not quite sure where to go from here. 该错误消息如此模糊,以至于我不确定从何而来。 Perhaps I am using AJAX within Laravel in an overly complicated way? 也许我在Laravel中使用AJAX的方式过于复杂? I was trying to stick to the conventions of the framework as much as possible, but I am open to trying it a different way if that would make this problem easier. 我试图尽可能地遵循框架的约定,但是如果这样会使问题更容易解决,我愿意尝试以其他方式尝试。

I am assuming that getSalesForcast is a scope so it should return a collection. 我假设getSalesForcast是一个范围,所以它应该返回一个集合。 I would recommend using forPage . 我建议使用forPage I am not 100% sure how you are getting your start date and end parameter in the request, but given those values this should work. 我不确定100%如何在请求中获取开始日期和结束参数,但是给定这些值应该可以工作。 Also, I am assuming you are using timestamps. 另外,我假设您正在使用时间戳。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM