dpgkg42484 2019-06-20 15:44
浏览 189

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

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.

I have a main blade file called reports.blade.php which contains an AJAX call to a controller method called 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. 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:

$.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:

<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:

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:

@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. 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? 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.

  • 写回答

1条回答 默认 最新

  • dsgni26260 2019-06-21 18:28
    关注

    I am assuming that getSalesForcast is a scope so it should return a collection. I would recommend using 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. 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'));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器