我有这个名为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>
当用户搜索某些帖子时,控制器的postSearch()函数返回一个JSON响应:
function postSearch() { $posts = $posts->select(...)->where(...)->orderBy(...)->paginate(5); //Search posts return Response::json(View::make('includes.posts',['posts' => $posts])->render()); }
并且jQuery在#posts div上附加HTML:
$('#search').submit(function(e) { e.preventDefault(); var form = $(this); $.post(form.attr('action'),form.serialize(),function(data) { $('#posts').html(data); }); });
这很完美.但现在当我点击分页链接时,页面重新加载,我的搜索结果消失了(显而易见).我如何分页这些帖子?我已经阅读了this,this和this文章,但我不明白如何实现它.
编辑
到目前为止,这是我的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']); }); });
不幸的是,没有任何反应,第1页的帖子一直在显示.
解决方法
@H_404_27@ 我对Laravel的分页不是很熟悉,但从你列出的链接来看,它看起来并不太难.此代码未经测试,但……$('#pagination a').on('click',function(e){ e.preventDefault(); var url = $(this).attr('href'); $.post(url,$('#search').serialize(),function(data){ $('#posts').html(data); }); });
更新
如果分页链接错误(就像OP的那些),你必须自己构建url.
只需要你想要的网址,并添加?page =#number.
// page being the page number stripped from the original link var url = $('#search').attr('action')+'?page='+page;