使用ajax分页获取查询字符串

问题描述 投票:2回答:1

我知道在添加->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')
    ]; 


}

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

php laravel octobercms
1个回答
0
投票

终于找到了一种解决方案,该解决方案可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.