【发布时间】:2014-12-30 04:23:06
【问题描述】:
如何更新我的视图以保留所有现有的 ajax 和 will_paginate 功能?
我有一个页面rehome.html.erb
<div id="options">Option Select Here</>
<div class="all_animals">
<%= render @animals %>
</div>
<% unless @animals.current_page == @animals.total_pages %>
<div id="infinite-scrolling">
<%= will_paginate @animals %>
</div>
<% end %>
// WILL_PAGINATE
<script type="text/javascript">
$(function(){
if($('#infinite-scrolling').size() > 0) {
$(window).on('scroll', function(){
//Bail out right away if we're busy loading the next chunk
if(window.pagination_loading){
return;
}
more_url = $('.pagination a.next_page').attr('href');
if(more_url && $(window).scrollTop() > $(document).height() - $(window).height() - 50){
//Make a note that we're busy loading the next chunk.
window.pagination_loading = true;
$('.pagination').text('Loading.....');
$.getScript(more_url).always(function(){
window.pagination_loading = false;
});
}
});
}
});
</script>
这将加载所有@animals 集合,将其分页为每页 6 个,当我向下滚动页面时,会加载另外 6 个等等。
对应的控制器
class PublicController < ApplicationController
before_filter :default_animal, only: [:rehome]
def rehome
respond_to do |format|
format.html
format.js
end
end
private
def default_animal
@animals = Animal.animals_rehome.paginate(:page => params[:page], :per_page => 6)
end
end
rehome.js.erb
$('.all_animals').append('<%= j render @animals %>');
<% if @animals.next_page %>
$('.pagination').replaceWith('<%= j will_paginate @animals %>');
<% else %>
$(window).off('scroll');
$('.pagination').remove();
<% end %>
因此,当从下拉列表中选择一个选项时,会创建一个 ajax 帖子以创建一个新查询,该查询将返回一个新的 @animals 集合
$.ajax({
type: 'POST',
url: '/public/rehomed',
data: data_send,
success: function(data) {
//console.log(data);
}
});
控制器
def rehomed
# conditions logic
@animals = Animal.joins(:user).where(conditions).paginate(:page => params[:page], :per_page => 6)
respond_to do |format|
format.js {render json: @animals }
end
end
我想要做的是加载新集合(再次分页到每页 6 个),当我向下滚动时,只显示属于 @animals 新集合的对象(如果有的话)。
目前分页链接没有更新,因为当我向下滚动页面时加载了原始集合。
编辑
所以我创建了一个rehomed.js.erb 文件,它与我的rehome.js.erb 几乎相同:
$('.all_animals').empty();
$('.all_animals').append('<%= j render @animals %>');
<% if @animals.next_page %>
$('.pagination').replaceWith('<%= j will_paginate @animals %>');
<% else %>
$(window).off('scroll');
$('.pagination').remove();
<% end %>
在我的重新行动中
respond_to do |format|
format.js
end
因此加载了新的动物集合,重新创建了分页链接,但使用了重新设置的 url,例如:
之前
<a class="next_page" href="/public/rehome?page=2" rel="next">Next →</a>
之后
<a class="next_page" href="/public/rehomed?page=2" rel="next">Next →</a>
所以当我向下滚动时,我只会得到以下内容,因为链接不存在并且 getScript 失败
$('.pagination').text('Loading.....');
编辑 2
我已经实现了@japed 的答案,但是现在在呈现新集合后,分页将继续呈现数据库的整个集合,包括重复为新集合选择的那些,它正在重复自身。
如何确保为我的链接生成正确的 url?
【问题讨论】:
-
我有点困惑你的问题是什么。您只需要单击您的选择或 onchange 事件活页夹
-
@japed 道歉,我已经更新了我的问题,希望能进一步解释事情
标签: javascript jquery ruby-on-rails ajax will-paginate