使用Kaminari

我正在尝试通过遵循本教程Ajax Pagination on Rails and Kaminari来使用Kaminari更新AJAX调用的分页网址。目前,我的分页正常,URL得到更新,但是我有两个问题:

  • 它不断在控制台中抛出此错误:Uncaught Error: rails-ujs has already been loaded!
  • 当我第一次单击分页链接时,内容会更改,但url不会更改(但是没有错误)。第二次单击时,URL和内容都将更新,但前面提到的错误仍显示在浏览器的控制台中。

如何改善我的代码?

错误:

VM780:8046 Uncaught Error: rails-ujs has already been loaded!
    at Object../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js.Rails.start (<anonymous>:8046:17)
    at Module../app/javascript/packs/application.js (<anonymous>:3021:101)
    at __webpack_require__ (<anonymous>:20:30)
    at <anonymous>:84:18
    at <anonymous>:87:10
    at DOMEval (<anonymous>:31283:14)
    at Function.globalEval (<anonymous>:31479:7)
    at Object.dataFilter (<anonymous>:39668:16)
    at ajaxConvert (<anonymous>:39108:22)
    at done (<anonymous>:39551:20)

posts#controller中:

  def index
    search = params[:search].present? ? params[:search] : nil

    @posts = if search
               # Render search results
               Post.search(params[:search],page: params[:page],per_page: 20)
             else
               # Render posts
               Post.all.order(created_at: :desc).page(params[:page])
             end

    # Get posts size
    @posts_size = Post.all.size
  end

index.js.erb中:

<%# Render posts %>
$("#posts").html("<%= j render(@posts) %>");
<%# Render pagination %>
$("#paginate").html("<%= j paginate(@posts,remote: true) %>");
$(document.body).on('click','nav.pagination a',function() {
    var url = $(this).attr("href")
    $(document.body).load(url,function() {
    <%# push state after the content has finished loading to update the URL and save in history stack %>
    window.history.pushState(url,window.title,url);
    <%# Scroll to top of the page %>
    $(document).scrollTop(0);
});
return false;
});
$(window).bind('popstate',function(event) {
    var url = location.href;
    <%# Reload HTML once user presses back / forward button %>
    $("#posts").load(url);
});
ief111111 回答:使用Kaminari

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2347082.html

大家都在问