Rails Ajax escape_javascript

时间:2019-02-25 19:41:17

标签: javascript ruby-on-rails ajax render

在这里,我已经使用Ajax设置了Rails应用程序,由于某种原因,我无法获得Ajax响应 在erb视图上。我猜create.js上的<%= escape_javaScript%>是错的。

下面是发布项目的流程。

  1. 在edit.html.erb(Ajax)上发布“项目”
  2. item_controller def create
  3. create.js
  4. /users/_item.html.erb(呈现Ajax)

edit.html.erb

<div class="content content-item">
  <ol>
    <%= form_tag('/items', method: :post, remote: true) do %>
    <input type="text" name="text" pattern=".*\S+.*" required  size="23" maxlength="23" autocomplete="off" class="header-btn">
    <%= submit_tag "submit" ,:class => "header-btn" %>
    <% end %>
  </ol>
</div>
<div class="content content-item">
   <ol>
     <% if @items.present? %>
       <div id="item-content">
         <%= render partial: "users/item", collection: @items %>
       </div>
     <% end %>
   </ol>
</div>

item_controller

def create
  @item = Item.new(text: item_params[:text], user_id: current_user.id)

  #Ajax
  respond_to do |format|
    if @item.save
      format.html { redirect_to @item, notice: 'successfully'}
      format.json { render :show, status: :created, location: @item }

      format.js
    else
      format.html { render :new }
      format.json { render json: @item.errors, status: :unprocessable_entity }
    end
  end
end

create.js(要点)

$("<%= escape_javascript(render partial: '/users/item', collection: 
@item ) %>").appendTo("#item-content");
//after submitting it makes textarea blank. 
$('form').find("textarea,:text,select").val("").end().find(":checked").prop("checked", false);

_item.html.erb

<div class="idea-text">
 <div  class="checked-item_<%= "#{item_counter}"%>" >
     <%= item.text  %>
 </div>
</div>//The rest is omitted 

过帐的数据完全保存在数据库中。 我可以在终端上看到它们

但未显示在edit.html.erb上。 我认为create.js应该有问题。

终端(发布后)

Started POST "/items" for ::1 at 2019-02-25 11:32:55 -0800
Processing by ItemsController#create as JS
Parameters: {"utf8"=>"✓", "text"=>"hello world", "commit"=>"submit"}
User Load (1.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 
3  ORDER BY `users`.`id` ASC LIMIT 1
Unpermitted parameters: utf8, commit
 (0.4ms)  BEGIN
SQL (40.8ms)  INSERT INTO `items` (`text`, `user_id`, `created_at`, 
`updated_at`) VALUES ('hello world', 3, '2019-02-25 19:32:55', '2019- 
02-25 19:32:55')
(52.3ms)  COMMIT
Rendered users/_item.html.erb (0.1ms)
Rendered items/create.js.erb (4.4ms)
Completed 200 OK in 151ms (Views: 22.9ms | ActiveRecord: 94.7ms)

0 个答案:

没有答案