weixin_33738555 2015-08-10 15:30 采纳率: 0%
浏览 33

Ajax调用在Rails中重复

I want to make comment form with Ajax call.

# app/views/comments/index.html.erb
<div id="comment_section">
  <%= render @comments %>
</div>
<%= form_for(@comment, remote: true) do |f| %>
  <%= f.input :contents %>
<%= f.submit %>

# app/vies/comments/_comment.html.erb
<p><%= comment.content %></p>

# app/controllers/comments_controller.rb
def create
  @comment = Comment.create(comment_params)
  respond_to do |format|
    format.js
  end
end

# app/views/comments/create.js.erb
$("#new_comment").bind("ajax:success", function(){
  $("#comment_section").prepend("<%= j render 'comment', locals: { comment: @comment } %>");
});

I thought it is very simple and there is no chance to have any errors. When I submit the form for the first time(e.g. contents = "a"), it makes no error and just one comment is prepended in the comment_section. But when I submit forms after that(e.g. contents = "b" , contents = "c"), it always prepend comments which was created before.

1st time(submit content = "a")

  • a(in the comment_section)

2nd time(submit content = "b")

  • b
  • a(I don't know why it appears)
  • a(first created one)

3rd time(submit content = "c")

  • c
  • b(it occurs again)
  • a(it occurs again)
  • b(second)
  • a(second)
  • a(first one)

What is going on? Log just says there was just one query and one render for new comment. After refreshing the page, it appears right.

After refresh

  • c
  • b
  • a

What am I missing? I don't know jQuery and Ajax well so I doubted turbolink could make some errors for this.(just my own guess) Any comments will be a huge help for me, thanks!

  • 写回答

1条回答 默认 最新

  • local-host 2015-08-10 15:39
    关注

    you're probably getting duplicate calls to the binded event. (add a console log to check)

    There's no need to bind an ajax:success event. (try to understand why you even inserted that because you do not need to). Your remote .js will go to that "create.js.erb code" so try removing the binded event and just use the $().prepend line of code by itself.

    评论

报告相同问题?

悬赏问题

  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?