pushState with Rails ajax

风格不统一 提交于 2019-12-01 05:57:25

I was in a similar situation and this is how I solved it. I am not sure whether this will work with Kaminari since I have no idea, how kaminari works.

#index.html.erb
<div class="grid">
  <%= render(@coasters) %>
</div>
<div class="pagination">
  <%= paginate @coasters, remote: true %>
</div>

--

#index.js.erb
$('.grid').html('<%= escape_javascript render(@coasters) %>');
$('.pagination').html('<%= escape_javascript(paginate(@coasters, remote: true).to_s) %>');

On pagination, since data-remote is enabled they will render index.js.erb only.

In my JavaScript

  $(document).on('click', '.pagination a[data-remote=true]', function(e) {
    history.pushState({}, '', $(this).attr('href'));
  });

  $(window).on('popstate', function () {
    $.get(document.location.href)
  });

On clicking on the pagination links, data-remote will be handle the ajax request and render index.js.erb

But on clicking the back button of browser the popstate event will be fired and current url in the browser will be link from history. SO we fire another ajax request with that url with $.get(document.location.href). This will have the same effect of clicking on the previous in pagination.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!