首页 > 解决方案 > 使用ajax分页获取查询字符串

问题描述

当您添加类似->appends(['location' => $search]). 当您使用分页时,它甚至可以将搜索查询保存到下一页。现在我使用 ajax 进行分页,我有这个 js 代码

<script type="text/javascript">

//Pagination part
    $('.main-section').on('click', '.pagination > li > a', function (event) {
    var page = $(this).text();
    event.preventDefault();
    if ($(this).attr('href') != '#') {
        $("html, body").animate({scrollTop: 0}, "slow");
        $.request('onFilterProduct', {
            data: {page: page},

        });
    }
});
</script>

我的 php 块有这个

function onFilterProduct(){

$slug = $this->param('slug');
 $search = Input('location');

$this['ads'] = Advert
::withCount(['ratings as rating' => function ($query) {
    $query->select(DB::raw('COALESCE(avg(rating), 0)'));
}])
->whereHas('cats', function ($query) use ($slug){
                  $query->where('slug',$slug);
               })->where('location', 'LIKE', "%{$search}%")
               ->orderBy('created_at','desc')->paginate(1)->appends(['location' => $search]);
                 return [
        '#product-list' => $this->renderPartial('product-filter-partial')
    ]; 


}

当我加载第一页时,一切正常并获得正确的页码,但是当我单击第二页时,它会重置所有内容,并且分页不再适用于位置查询字符串。请问我该如何解决这个问题。

标签: phplaraveloctobercms

解决方案


终于找到了一个使用javascript pushState api更新页面url而无需重新加载的解决方案

 history.pushState(null, null, $(this).attr('href')); 

所以我的 js 代码现在看起来像这样

<script type="text/javascript">

//Pagination part
    $('.main-section').on('click', '.pagination > li > a', function (event) {
    var page = $(this).text();
    event.preventDefault();
    if ($(this).attr('href') != '#') {

        // Update the browser's address bar
        history.pushState(null, null, $(this).attr('href'));  

        $("html, body").animate({scrollTop: 0}, "slow");
        $.request('onFilterProduct', {
            data: {page: page},

        });
    }
});
</script>

推荐阅读