Ajax Search with pagination [Laravel]



我已经用Laravel阅读了 https://gist.github.com/tobysteward/6163902 和AJAX分页,但似乎我遇到了不同的问题,所以无论如何。

长话短说:当我搜索时,会获取正确的数据,并且 ajax 只对第一页工作"显示数据,不刷新",但从下一页开始页面刷新,那么如何进行 ajax 调用,循环遍历返回的数据并根据每个页面显示它?

还有如何将搜索查询添加到 URL,目前当数据被获取时,URL 不会更新,而是保持其当前状态(即 index?page=3 )。

搜索表单

{{ Form::open(['route' => 'search', 'method' => 'GET', 'id' => 's-form',])}}
    {{ Form::text('search', null, ['id' => 'search', 'placeholder' => 'Search For ...']) }}
    {{ Form::submit(Go) }}
{{ Form::close() }}

搜索控制器

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);
}

搜索视图

@forelse ($posts as $post)
        // do stuff
@endforeach
<nav>{{ $posts->appends(Request::except('page'))->links() }}</nav>

JS的

$('#s-form').submit(function(e)
{
    e.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        data:{
            search: $('#search').val()
        },
        success: function(data){
            $('#result').html(data);
        }
    });
});

这就是它所需要的:

$(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);
            }
        });
    });
});

现在我只需要根据每个页面更新 URL。

最新更新