【问题标题】:Rails 5, simple javascript with form submitRails 5,带有表单提交的简单javascript
【发布时间】:2018-03-25 21:02:25
【问题描述】:

我希望有人可以在这里帮助我。在这里待了几个小时,但似乎无法弄清楚为什么我的 Javascript 不能在我的简单表单上运行。我只是想使用 ajax 调用显示 cmets。我的 application.js 文件中有 gem 'jquery-rails' 和必需的 jquery 和 jquery_ujs。这是我到目前为止的代码:

我有一个 Joy 模型,它有_many cmets。

<% @joys.each do |joy| %>

<ul id="comments-<%= joy.id %>">
  <% joy.comments.where(void:'f').each do |comment| %>
    <li><%= comment.body %></li>
  <% end %>
</ul>

<%= form_with(model: [ joy.user, joy, joy.comments.build ], data:{ "js-comments-#{joy.id}" => true}) do |f| %>
  <%= f.text_area :body, :class=>'form-control', :required=>'true' %>
  <%= f.submit "Post Comment" %>
<% end %>

<script>
  $(document).ready(function() {
    $('[data-js-comments-<%= joy.id %>]').on("ajax:success", function(event, data, status, xhr){
      $('#comments-<%=joy.id%>').append(xhr.responseText);
    });
  });
</script>

<% end %>

在我的评论控制器中,在我的“创建”操作中,我有:

if @comment.save
  render partial: "comment", locals: {comment: @comment}
end

在我的评论视图中,我创建了一个名为 _comment.html.erb 的部分视图:

<li>
    <%= comment.body %>
</li>

所以,现在当我输入评论并单击“发表评论”时,它会正确保存我的评论,但它不会将评论加载到列表中。此外,表单也不刷新。文本保留在文本框中。直到我刷新页面后,我的评论才会出现在列表中。任何人对我错过了什么或做错了什么有任何想法???

非常感谢您的帮助。

【问题讨论】:

  • 你在使用turbolinks吗?
  • @jvillian 我不这么认为。

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-5


【解决方案1】:

form_with 这是一个远程表单,你不需要那个块&lt;script&gt;..&lt;/script&gt;。 只需使用create.js.erb,然后使用 jquery 追加新评论。

如果你想检查你的消息是否创建成功,你可以在你的控制器中添加一个@status 值。

//comments_controller.rb
def create
  ...
  if @comment.save
    @status = "success"
  else
    @status = "failed"
  end
  ...
end

//create.js.erb - for example
 $("#yourCommentList").append('<%= j( render partial: 'comments/comment', locals: @comment ) %>');
 <% if @status == "success" %>
   $("body").append(...your notification...)
    ...
 <% else %>
    ...
 <% end %>

【讨论】:

  • 嗨@Dapeng114 - 我试过这个,但仍然无法让评论填充。现在,当我尝试运行它时遇到 POST javascript 错误。
猜你喜欢
  • 2017-07-25
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2016-06-06
  • 1970-01-01
  • 2013-04-14
相关资源
最近更新 更多