Jas*_*onK 10 ajax search jquery pagination laravel
我有这个视图posts.blade.php,其中包括home.blade.php:
<div id="posts">
@foreach ($posts as $post)
<div class="list-item clearfix">
<div class="content">
<img src="{{ URL::to($post->thumbnail) }}" alt="" />
<h1>{{{ $post->title }}}</h1>
</div>
<div class="score">{{ $post->rating }}</div>
</div>
@endforeach
<div id="pagination">{{{ $posts->links() }}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)
当用户搜索某些帖子时,控制器的postSearch()函数会返回JSON响应:
function postSearch()
{
$posts = $posts->select(...)->where(...)->orderBy(...)->paginate(5); //Search posts
return Response::json(View::make('includes.posts', ['posts' => $posts])->render());
}
Run Code Online (Sandbox Code Playgroud)
并且jQuery在#postsdiv 上附加HTML :
$('#search').submit(function(e) {
e.preventDefault();
var form = $(this);
$.post(form.attr('action'), form.serialize(), function(data) {
$('#posts').html(data);
});
});
Run Code Online (Sandbox Code Playgroud)
这很完美.但现在当我点击分页链接时,页面重新加载,我的搜索结果消失了(显而易见).我如何分页这些帖子?我读过这个,这个和这个文章,但我不知道如何实现它.
编辑
到目前为止,这是我的jQuery分页:
$('#posts').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href'),
page = url.split('page=')[1],
data = $('#search').serializeArray();
data.push({page: page}); // Add page variable to post data
console.log(data);
$.post($('#search').attr('action'), data, function(data) {
$('#posts').html(data['posts']);
});
});
Run Code Online (Sandbox Code Playgroud)
这是我点击分页链接时发送的数据(第2页):

不幸的是,没有任何反应,第1页的帖子一直在显示.
我对Laravel的分页不是很熟悉,但从你列出的链接来看,它看起来并不太难.此代码未经测试但是......
$('#pagination a').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.post(url, $('#search').serialize(), function(data){
$('#posts').html(data);
});
});
Run Code Online (Sandbox Code Playgroud)
如果分页链接错误(就像OP的那些),你必须自己构建url.
只需获取您想要的网址并添加?page=#number到其中即可.
// page being the page number stripped from the original link
var url = $('#search').attr('action')+'?page='+page;
Run Code Online (Sandbox Code Playgroud)