我在我的ROR
项目中使用will_paginate
gem来显示页面中的记录。
我想要加载下一个页面,而不是使用ajax
重新加载整个页面。
我在网上找到了一些例子,但它们对我不起作用。
该怎么做呢?
发布于 2012-11-30 13:16:49
嘿,如果你想对产品进行分页,那么试试这个:
应用程序/控制器/products_Controler.rb
def index
@products = Product.paginate(page: params[:page], per_page: 10)
end
视图/产品/index.html.erb
<div class = "sort_paginate_ajax"><%= render 'products' %></div>
views/products/_products.html.erb
<% @products.each do |product| %>
# your code
<% end %>
<%= will_paginate @products %>
视图/产品/index.js.erb
$('.sort_paginate_ajax').html("<%= escape_javascript(render("products"))%>")
assets/javascripts/application.js
$(function() {
$(".sort_paginate_ajax th a, .sort_paginate_ajax .pagination a").on("click", function(){
$.getScript(this.href);
return false;
});
});
因此,首先我们在所有产品的产品上调用paginate方法,这里将根据params[:page]
设置偏移量,并通过per_page
选项设置限制。此外,我们正在呈现products
部分,它将在每次打开其他页面时呈现。
在对你想要的@products
的部分调用中,然后在@products
上应用will_paginate
方法,它还创建了控制器中使用的params[:page]
。
现在,为了响应ajax请求,使用我们创建的部分内容呈现具有类sort_paginate_ajax
的div
内容。
还可以请求ajax请求,对文档加载捕获脚本中的所有div.sort_paginate_ajax
标签,并返回false。
现在将使用ajax请求调用页面
我希望这能对你有所帮助。
发布于 2015-05-22 19:01:55
对先前答案的补充。
代码字符串:
$(".sort_paginate_ajax th a, .sort_paginate_ajax .pagination a").on("click", function(){
替换为字符串:
$(".sort_paginate_ajax").on("click", ".pagination a", function(){
onclick事件仅应用于已存在的元素。因此,对于新出现的链接,需要将点击事件从父级".sort_paginate_ajax“委派给子级".pagination a”。
发布于 2016-06-14 08:24:04
你可以直接使用JQuery:
控制器:
def index
@posts = Post.paginate(:page => params[:page])
respond_to do |format|
format.html
format.js
end
end
然后在index.html.erb中:
<div id="post-content", posts: @posts >
<%= j render 'post_content' %>
</div>
在部分‘_post_content.html.erb’中:
<%= will_paginate @posts %>
<% @posts.each do |post| %>
<p><%= post.content %></p>
<% end %>
pagination.js:
$(document).ready(function() {
$('.pagination > a').attr('data-remote', 'true');
});
index.js.erb:
$('#post-content').html("<%= j render 'post_content' %>")
请确保将
$('.pagination > a').attr('data-remote', 'true');
同样在您的JS模板(index.js.erb)中,因此当Ajax运行时,它再次将链接设置为远程的。
https://stackoverflow.com/questions/13623953
复制相似问题