php - 使用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')
];
}
当我加载第一页时,一切正常并获得正确的页码,但是当我单击第二页时,它会重置所有内容,并且分页不再适用于位置查询字符串。请问我该如何解决这个问题。
解决方案
终于找到了一个使用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>
推荐阅读
- c++ - 如何修复我的 C++ 代码?(不匹配运算符)
- php - 如何从已完成的订单中删除一个项目 (wc_delete_order_item ())
- vue.js - VueJs图像未显示
- selenium - Selenium IDE Web 驱动程序 Chrome
- google-apps-script - 为什么我的共享用户不能使用我在 Google 表格中写入的脚本?
- python - 带有 Python 的 Google 表格 API
- python - 如何修改 Pytorch 中的 loss.backward() 以解决 np.nan 的问题?
- javascript - 按钮 OnClick 仅返回适用于第一个元素
- python - Python:写长度控制
- yaml - 如何在 Swagger Codegen (Gradle) 中为 OpenAPI 3.0 指定 templateDir?