在提交表单后尝试使用 ajax 更新 DIV。
我的部分_inline.html.erb是
<div class="large-12 columns" id="inline_posts">
<% @posts.each do |post| %>
<div class="row">
<div class="large-10 columns left"><%= post.content %></div>
<div class="large-2 columns right"><%= link_to 'Remove', post, method: :delete, class: 'tiny button' %></div>
</div>
<% end %>
</div>
我的js.erb是
$('#inline_posts').html("<%= j render 'posts/inline' %>");
$('#new_post').html("<%= j render 'posts/form' %>");
重新渲染表单没问题。表单重新绘制,就像新的一样。
DIV 的呈现是问题所在。它呈现新的 DIV 而不是旧的 DIV。为什么它不像替换现有表单那样替换现有的 DIV?
通过 AJAX 更新后的 DIV 看起来像
<div class="large-12 columns" id="inline_posts">
<div class="large-12 columns" id="inline_posts">
将它的新版本放在旧版本中。
编辑:
表单 HTML
<div class="large-12 columns"> <--- Note this has no id specified
<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
<div style="display:none"><input name="utf8" type="hidden" value="✓" /></div>
<div class="row">
<div class="large-12 columns">
<label for="post_Post a message">Post a message</label>
</div>
</div>
<div class="row">
<div class="large-10 columns">
<textarea class="form-control" id="post_content" name="post[content]">
</textarea>
</div>
<div class="large-2 columns">
<input class="button" name="commit" type="submit" value="Post" />
</div>
</div>
</form>
</div>
表单部分 posts/_form.html.erb(这将创建一个 ID 为“new_post”的表单)
<%= form_for(@post, remote: true) do |f| %>
<div class="row">
<div class="large-12 columns">
<%= f.label 'Post a message' %>
</div>
</div>
<div class="row">
<div class="large-10 columns">
<%= f.text_area :content, class: 'form-control' %>
</div>
<div class="large-2 columns">
<%= f.submit 'Post', class: 'button' %>
</div>
</div>
<% end %>
最佳答案
.html
只是 .innerhtml
的优雅包装器所以无论 posts/inline
呈现什么将被放置在 inline_posts
内分格标签
您可能想尝试 replaceWith()
$('#inline_posts').replaceWith("<%= j render 'posts/inline' %>");
如果你想要那个元素#inline_posts
替换为 posts/inline
呈现的内容
编辑:
当你打电话时,$('#inline_posts').html("<%= j render 'posts/inline' %>");
您基本上是在使用 posts/inline
中的 html模板文件并将其放在 inline_posts
中div,像这样:
<div class="large-12 columns" id="inline_posts">INSERTING posts/inline HTML HERE</div>
你的 posts/inline
模板文件必须以<div class="large-12 columns" id="inline_posts">
开头否则你不会得到你正在得到的结果。
它适用于您的表单,因为您的 posts/form
模板文件不以 <form id="new_posts">
开头因此,您的帖子文件中的 html 会在该元素内呈现,如下所示:
<form id="new_posts">INSERTING posts/form HTML HERE</form>
form#new_posts
不是模板文件的一部分,其中 div#inline_posts
必须是其各自模板文件的一部分。这就是为什么你要嵌套一个而不是另一个。
我希望这是有道理的。
关于javascript - Rails/Ajax 不替换 DIV,而是将新的 DIV 嵌套在旧的 DIV 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24639677/