weixin_33739541 2016-06-21 12:09 采纳率: 0%
浏览 88

对ajax的无限请求

I am working on an app where user can heart(like) stories. I am trying to implement it with ajax. I have a StoriesController with the heart action. Whenever the heart(like) is clicked, I have responded with heart.js.erb and send a post request. I am working on to update the number of hearts when the user clicks the heart link. But what I am getting is infinite requests via ajax. Below is the snippet of heart action.

# Give your heart to someone
  def heart
    respond_to do |format|
      format.js
      format.html
    end
  end

And ajax request is:

$('#heart-story-<%= j params[:id]%>').html('<%= @hearts %>')
$.post("/stories/<%= j params[:id]%>/heart", <%= j params[:id] %>)
console.log("<%= j params[:id] %>")

What is the probable reason that I am getting infinite request? The route is:

#Stories
resources :stories, only: [:show, :create, :destroy] do
member do
  get :heart, :unheart
  post :heart, :unheart
end
# Comments
resources :comments, only: [:index, :new, :create, :destroy]
end
  • 写回答

2条回答 默认 最新

  • weixin_33737134 2016-06-21 12:19
    关注

    If you have specified following code in heart.js.erb then it will be infinite:

    $('#heart-story-<%= j params[:id]%>').html('<%= @hearts %>')
    $.post("/stories/<%= j params[:id]%>/heart", <%= j params[:id] %>)
    console.log("<%= j params[:id] %>")
    

    Post request should only be triggered on button click for once don't use it in heart.js.erb

    评论

报告相同问题?