will_paginate沒有本機AJAX支持,但確實提供切換鏈接呈現。添加以下類RAILS_ROOT/lib添加到remote_link_renderer.rb,使鏈路的AJAX回調渲染視圖適合:
class RemoteLinkRenderer < WillPaginate::LinkRenderer
def prepare(collection, options, template)
@remote = options.delete(:remote) || {}
super
end
protected
def page_link(page, text, attributes = {})
@template.link_to_remote(text, {:url => url_for(page), :method => :get}.merge(@remote))
#replace :method => :post if you need POST action
end
end
使用此在您的觀點呈現分頁鏈接(需要定製):
<%= will_paginate(@results, :params => {:controller => :mycontroller, :action => :search, :query => h(@query)}, :renderer => RemoteLinkRenderer, :page_links => false) %>
由於您需要替換呈現這些分頁鏈接和結果的視圖,控制器會變得更棘手。我使用的是這樣的:
if request.xhr? or request.post?
if params[:page]
render :update do |page|
page.replace_html :search_results, :partial => 'mycontroller/search_results', :layout => false
end
else
render :partial => 'mycontroller/search_results'
end
else
# Render some normal content here
end
我跟着這個[鏈接](http://asciicasts.com/episodes/240-search-sort-paginate-with-ajax),並得到了它的工作,jQuery代碼做訣竅! – Magesh