0
ページを再読み込みせずにdivを更新するために、jquery with railsでJavaScriptを使用しようとしています。その作業はしていますが、コメントは2回作成されています。私は何かが部分的な形で間違っていることを知っていますが、それを理解できませんでした。どんな助け?link_toを送信するフォームが2回あるのはなぜですか?
_new_comment.html.erb
<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %>
<div>
<%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %>
<%= f.hidden_field :post_id, :value => post.id %>
<span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span>
</div>
<% end %>
comments_controller.rb
def create
@comment = Comment.new(comment_params)
@comment.user_id = current_user.id
if @comment.save
flash[:notice] = 'Comment added sucessfully'
respond_to do |format|
format.html { redirect_to home_posts_url }
format.js
end
end
end
create.js.erb
$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>');
$("#comment-new-83")[0].reset();
ホーム -
次のファイルです。 js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
$(document).ready(function() {
$("#comment-new-83").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), null, "script");
return false;
})
})
'リモートを削除します。link_to''からtrue'ををして試してみても ':onclick'。 –
どこでonclickを使用しますか? – Beginner1111
フォームに 'submit'イベントをバインドしているので、どこにでも':onclick'を置く必要はありません。 –