带分页的 Ajax 搜索 [Laravel]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27969577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax Search with pagination [Laravel]
提问by ctf0
I've read both https://gist.github.com/tobysteward/6163902& AJAX pagination with Laravelbut it seems I have a different problem so anyway.
我已经阅读了https://gist.github.com/tobysteward/6163902和Laravel 的 AJAX 分页,但似乎我有一个不同的问题,所以无论如何。
Long story short: When I search, the right data gets fetched and the ajax works "display data, no refresh" only for the first page, but from next page on the page refreshes, so how to make an ajax call that loop through the returned data and display it according to each page?
长话短说:当我搜索时,会获取正确的数据,并且 ajax 工作“显示数据,不刷新”仅适用于第一页,但从页面上的下一页开始刷新,那么如何进行循环的 ajax 调用返回的数据并根据每个页面显示?
Also how to add the search query to the URL, currently when the data gets fetched, the URL doesn't update, instead it stays on its current state (i.e. index?page=3
).
还有如何将搜索查询添加到 URL,当前当获取数据时,URL 不会更新,而是保持其当前状态(即index?page=3
)。
search form
搜索表格
{{ Form::open(['route' => 'search', 'method' => 'GET', 'id' => 's-form',])}}
{{ Form::text('search', null, ['id' => 'search', 'placeholder' => 'Search For ...']) }}
{{ Form::submit(Go) }}
{{ Form::close() }}
search controller
搜索控制器
public function search() {
$input = Input::get('search');
$posts = Post::where('title','LIKE',$input)->paginate(4);
if (Request::ajax()) {
return View::make('posts.search')->withPosts($posts);
}
return View::make('posts.index')->withPosts($posts);
}
search view
搜索视图
@forelse ($posts as $post)
// do stuff
@endforeach
<nav>{{ $posts->appends(Request::except('page'))->links() }}</nav>
the js
js
$('#s-form').submit(function(e)
{
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
data:{
search: $('#search').val()
},
success: function(data){
$('#result').html(data);
}
});
});
回答by ctf0
This is all it needed:
这就是它所需要的:
$(document).ajaxComplete(function() {
$('.pagination li a').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data) {
$('#result').html(data);
}
});
});
});
Now I just need to update the URL according to each page.
现在我只需要根据每个页面更新 URL。