问题
I've been reading through some posts on SO to see how others are handling this and the implementation i am using is almost there but fails after the third link requested, what happens is the page is reloaded as opposed to firing the ajax request. I have also removed Turbolinks but that hasn't made a difference.
This is my setup and I think the js is failing somewhere and as my jQuery is not that strong I was hoping someone could help out
Index.html.erb
<div class="facebook_ajax">
<%= render 'shared/posts' %>
</div>
shared/_posts.html.erb
<% @posts.each do |p| %>
<article class="post">
<%= image_tag('/assets/vandals_fb_profile.jpg') %>
<%= link_to 'Varsity Vandals', "https://www.facebook.com/VarsityVandals", target: 'blank' %>
<%= date_output(p.created_time) %>
<figure>
<% if p.large_image_url? %>
<%= image_tag(p.large_image_url) %>
<% end %>
<% if p.video_url? %>
<%= raw youtube_embed(p.video_url) %>
<% end %>
</figure>
<p><%= p.message.gsub("\n", "<br>").html_safe %></p>
<% if p.description? %>
<p><%= p.description %></p>
<% end %>
<%= link_to 'Read More', p.link %>
</article>
<hr/>
<% end %>
<%= will_paginate @posts, previous_label: '', next_label: '', page_links: false %>
index.js.erb
$('.facebook_ajax').html("<%= escape_javascript(render("shared/posts"))%>")
jQuery
<script>
$(document).ready(function () {
$(".facebook_ajax .pagination a").on("click", function(){
$.getScript(this.href);
return false;
});
});
</script>
So when clicking the next link for the first time ajax request completes fine, but upon the third click the page reloads and the url is changed to
?_=1399027258398&page=3
Does anyone know how to combat this please
Thanks
回答1:
Thought I would answer this so maybe it can help someone else, I had to delegate the event to a DOM element that was always there, so used the body tag for example
$(document).ready(function () {
$("body").on("click", '.facebook_ajax .pagination a', function(e){
e.preventDefault();
$.getScript(this.href);
return false;
});
});
My understanding that is once the first click is made you lose the oriiginal set of href's that where gathered
Good link Here
来源:https://stackoverflow.com/questions/23426363/ajax-request-with-will-paginate-rails-4