2015-01-15 94 views
0

我讀過https://gist.github.com/tobysteward/6163902 & AJAX pagination with Laravel但似乎我有一個不同的問題,所以無論如何。Ajax搜索與分頁[Laravel]

長話短說:當我搜索時,正確的數據被獲取並且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); 
     } 
    }); 
}); 
+0

你沒有在JavaScript中的任何地方傳遞頁面參數,這應該如何工作?分頁需要正確的參數,也沒有任何點擊處理程序來處理分頁通過JavaScript – pfried 2015-01-16 06:59:40

+0

是的,我知道,但如何做到這一點?那是什麼實際上要求。 – ctf0 2015-01-16 07:00:22

+0

嘗試在ajax請求的數據部分中添加一個頁面參數,只需像數據一樣硬編碼一個數字:{search:$('#search')。val(),page:'2'} – pfried 2015-01-16 07:03:46

回答

2

這是所有需要:

$(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。

+0

你可以使用JavaScript的歷史API。作爲一個例子,請參閱http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page。由於你不重新加載頁面,你必須使用Javascript – pfried 2015-01-17 08:40:49

+0

thanx來完成這個建議,請試試看。 – ctf0 2015-01-17 09:34:07