Rails AJAX 注释清除文本区域

Posted

技术标签:

【中文标题】Rails AJAX 注释清除文本区域【英文标题】:Rails AJAX comments clear textarea 【发布时间】:2016-03-11 01:06:40 【问题描述】:

我正在我的网络应用程序上添加 AJAX cmets,但我不知道如何在添加评论后使 textarea(我写评论的地方)清晰。此外,我在使用 AJAX 时很难显示错误。

我的评论控制器:

  def create
    @user = User.find(params[:user_id])
    @guide = Guide.find(params[:guide_id])
    @comment = @guide.comments.build(comment_params)
    if @comment.valid?
      @comment.user = current_user
      @comment.save
      respond_to do |format|
        format.html 
          flash[:notice] = "Comment added!"
          redirect_to :back
        
        format.js
      end
    else
        flash[:danger] = "Comment must be 4 to 200 letters long"
        redirect_to :back
      end
    end
  end

JS 文件(create.js.erb):

$(".comments").html("<%= escape_javascript(render @guide.comments) %>);

查看(指南/show.html.erb):

    ...
     <div class="add_comment">
        <%= form_for [@user, @guide, Comment.new], remote: true  do |f| %>
          <p>
            <%= f.text_area :body %>
          </p>
          <p><%= f.submit "Add comment" %></p>
        <% end %>
      </div>
      <div class="comments">
        <%= render @guide.comments %>
      </div>

还有我的部分评论(_comment.html.erb):

<%= div_for comment do %>
  <div id="comment">
    <%= link_to image_tag(comment.user.avatar(:small)), comment.user %>
    <small><%= link_to " #comment.user.username ", comment.user %> <%= time_ago_in_words(comment.created_at) %> ago.
    <% if comment.user == current_user || current_user.admin? %>
      <%= link_to "Delete", user_guide_comment_path(comment.user, comment.guide, comment), method: :delete, data:  confirm: "Are you sure?" %>
    <% end %>
    </small>
    <br/>
    <span><%= comment.body %></span>
  </div>
<% end %>

要清除 - 我希望添加新评论“AJAX TEST COMMENT”的区域在单击提交并添加评论后自行清除,另外任何关于如何使用 AJAX 显示错误的建议将不胜感激。

编辑:是的 - 代码确实添加了新注释并通过 ajax 呈现所有 cmets 而无需刷新整个页面。

Started POST "/users/1/guides/103/comments" for 127.0.0.1 at 2015-12-06 11:59:53 +0100
Processing by CommentsController#create as JS
  Parameters: "utf8"=>"✓", "comment"=>"body"=>"AJAX ANOTHER TEST COMMENT - IT IS WORKING", "commit"=>"Add comment", "user_id"=>"1", "guide_id"=>"103"
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Guide Load (0.1ms)  SELECT  "guides".* FROM "guides" WHERE "guides"."id" = ? LIMIT 1  [["id", 103]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.2ms)  INSERT INTO "comments" ("body", "guide_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["body", "AJAX ANOTHER TEST COMMENT - IT IS WORKING"], ["guide_id", 103], ["user_id", 1], ["created_at", "2015-12-06 10:59:53.334245"], ["updated_at", "2015-12-06 10:59:53.334245"]]
   (42.3ms)  commit transaction
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."guide_id" = ?  ORDER BY "comments"."created_at" DESC  [["guide_id", 103]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Rendered comments/_comment.html.erb (13.8ms)
  Rendered comments/create.js.erb (15.8ms)
Completed 200 OK in 65ms (Views: 17.1ms | ActiveRecord: 43.3ms)

【问题讨论】:

你能确认这是现在保存,并且还渲染所有@guide.comments吗? 是的 - 它正在保存评论。添加日志以证明这一点。另外添加了我忘记在那里发布的评论部分。 【参考方案1】:

在控制器中重构 create 方法如下:

  def create
    @user = User.find(params[:user_id])
    @guide = Guide.find(params[:guide_id])
    @comment = @guide.comments.build(comment_params)
    @comment.user = current_user
    @comment.save
    respond_to do |format|
      format.html 
        flash[:notice] = "Comment added!"
        redirect_to :back
      
      format.js
    end
  end

这里,控制器没有处理错误,我们将继续在create.js.erb文件中执行此操作,并显示flash如下:

$(".comments").html("<%= escape_javascript(render @guide.comments) %>");
$('#comment_body').val('');
<% if @comment.errors.empty? %>
  $("#notice").html("Comment was successfully posted.");
<% else %>
  $("#notice").html("Error! Comment not posted.");
<% end %>

这是假设您在页面上有 #notice div - (这通常出现在每个 rails 应用程序页面上,因为它来自 application.html.erb

同样的方法可用于将@comment 中的错误附加到来自create.js.erb 的页面

【讨论】:

我遇到了错误 - 不得不将你的代码稍微改成这样:&lt;% if @comment.errors.empty? %&gt; $(".comments").html("&lt;%= escape_javascript(render @guide.comments) %&gt;"); $('#comment_body').val(''); &lt;% else %&gt; $("#notice").html("Error! Comment not posted."); &lt;% end %&gt; 谢谢你的帮助 - 它就像一个魅力!【参考方案2】:

我设法通过简单地添加来清除文本区域:

$(".comments").html("<%= escape_javascript(render @guide.comments) %>");
$('#comment_body').val('');

现在只剩下第二个问题了——如何通过 ajax 显示错误、flash[messages] 等?我认为值得一提的是我有部分错误消息(_error_messages.html.erb):

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

【讨论】:

以上是关于Rails AJAX 注释清除文本区域的主要内容,如果未能解决你的问题,请参考以下文章

如何清除焦点上的文本区域?

使用 Ruby on Rails 在文本区域中保留换行符

Ajax 将格式化文本传递给另一个 php 文件并显示为在文本区域中

Html 文本区域占位符

点击按钮后在两个文本区域中添加新行并用文本填充它们

自动清除和重新填充文本区域值