Ajax请求返回三次而不是一次

时间:2014-12-12 16:09:00

标签: jquery ruby-on-rails ruby ajax

我正试图用" will_paginate" gem和Ajax,但当我点击按钮加载下一页帖子时,Ajax会为每个帖子返回三次。

这是我的控制者:

class PublicCampaignController < ApplicationController
  def index
    @posts = Post.where(campaign_id: params[:id]).order(created_at: :desc).page(params[:page]).per_page(5)
    @campaign = Campaign.find(params[:id])

    respond_to do |format|
        format.html { render layout: 'public_campaign_layout' }
        format.js
    end
  end

end

查看:

Index.html.erb:

 <div class="pageheader">
  <div class="row">
    <div class="col-sm-4">
    </div>
    <div class="col-sm-4 campaign_title">
      <h4><%= @campaign.name %></h4>
    </div>
    <div class="col-sm-4">
      <span class="powered_text"> Powered by <%=link_to "Pindle", "http://www.getpindle.com", target:'_blank' %></span>
    </div>
  </div>
</div>
<% if @posts.present? %>
  <div id="list" class="posts">
    <%= render :partial => 'posts', :locals => { :posts => @posts } %>
  </div><!--end list-->
  <div class="loadmoreposts">
    <%= link_to 'Load More Posts', public_campaign_path(params[:id], @posts.next_page), :class => 'btn btn-default load-more-posts', :remote => true if @posts.next_page %>
  </div>
<% end %>

Ajax响应:

$('.posts').append('<%= escape_javascript(render :partial => "posts", :locals => { :posts => @posts }) %>');
$('a.load-more-posts').attr('href', "<%= public_campaign_path(params[:id], @posts.next_page) %>");

<% unless @posts.next_page %>
  $('a.load-more-posts').remove();
<% end %>

使用Javascript:

应用:

//= require jquery
//= require jquery_ujs
//= require turbolinks

//= require jquery.infinitescroll.js
//= require bootstrap.min.js
//= require campaigns.js.coffee
//= require feeds.js.coffee
//= require jquery-migrate-1.2.1.min.js
//= require jquery-ui-1.10.3.min.js
//= require jquery.cookies.js
//= require jquery.sparkline.min.js
//= require modernizr.min.js
//= require posts.js.coffee
//= require public_campaign.js.coffee
//= require retina.min.js
//= require toggles.min.js
//= require custom.js

//= require_self

public_campaign.js.coffee:

$ ->
  loading_posts = false
  $('a.load-more-posts').on 'click', (e, visible) ->
    return if loading_posts #or not visible
    loading_posts = true
    $.getScript $(this).attr('href'), ->
      loading_posts = false

路线:

get 'p/:id/:page' => 'public_campaign#index', as: :public_campaign

当我点击&#34;加载更多帖子&#34;:

时会发生这种情况
13:03:15 web.1  | 127.0.0.1 - - [12/Dec/2014 13:03:15] "GET /p/8/2?_=1418400189605 HTTP/1.1" 200 - 0.0218
13:03:15 web.1  | 127.0.0.1 - - [12/Dec/2014 13:03:15] "GET /p/8/2 HTTP/1.1" 304 - 0.0269
13:03:15 web.1  | 127.0.0.1 - - [12/Dec/2014 13:03:15] "GET /p/8/2?_=1418400189606 HTTP/1.1" 200 - 0.0324

0 个答案:

没有答案