这是一个简单的购物清单应用程序。左列div是列表列表。特定列表的项目显示在右栏div中。
以下是流程:
用户点击其中一个列表,然后在右侧div中加载(AJAX)它的相关项目。这很好。
这是我被困的地方:
项目上方是一个输入字段,用于将新项目提交到下面的项目列表中。我希望AJAX将新项目添加到下面的项目中,但是当我在表单字段上按Enter键时,没有任何反应。刷新时,会添加新项目。
以下是服务器所说的内容:
Processing by ItemsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YWIlMPXqoTvhqzGGPqm6Rn/E7jPRt8do/2tkjd0H1Qk=", "item"=>{"name"=>"Mayo"}, "list_id"=>"4"}
List Load (0.1ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? LIMIT 1 [["id", "4"]]
(0.0ms) begin transaction
SQL (20.9ms) INSERT INTO "items" ("completed", "created_at", "description", "list_id", "name", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["completed", false], ["created_at", Mon, 29 Apr 2013 21:59:06 UTC +00:00], ["description", nil], ["list_id", 4], ["name", "Mayo"], ["position", nil], ["updated_at", Mon, 29 Apr 2013 21:59:06 UTC +00:00]]
(1.6ms) commit transaction
Rendered items/_piece.html.erb (0.0ms)
Rendered items/create.js.erb (0.7ms)
以下是页面加载过程:
home.html.erb
> _single.html.erb
> create.js.erb
>将_piece.html.erb
添加到home.html.erb
这是我items_controller.rb
文件中的创建操作:
def create
@list = List.find(params[:list_id])
@item = @list.items.create!(params[:item])
respond_to do |format|
format.html
format.js
end
end
这是我的create.js
文件:
$('#item-container').prepend('<%= j render(partial: 'piece', locals: {item: @item}) %>');
这是我的_piece.html.erb文件:
<li><%= item.name %></l1>
这是我的_single.html.erb
文件:
<div id="filter">
<div id="filter-left">
</div>
<div id="filter-right">
<%= link_to 'Delete', @list, :method => :delete %>
</div>
</div>
<div id="quick-add">
<%= form_for [@list, @item], :id => "form-quick", remote: true do |form| %>
<%= form.text_field :name, :id => "input-quick", :autocomplete => "off" %>
<% end %>
</div>
<ul class="item-container">
<% @list.items.incomplete.each do |item| %>
<% if item.id %>
<li><%= link_to "", complete_item_path(@list.id,item.id), :class => "button-item button-item-incomplete" %> <%= item.name %></li>
<% end %>
<% end %>
</ul>
<div class="title">Completed items</div>
<ul class="item-container">
<% @list.items.completed.each do |item| %>
<% if item.id %>
<li><div class="button-item button-item-completed"></div><%= item.name %></li>
<% end %>
<% end %>
</ul>
这是我的home.html.erb
文件:
<div id="main-left">
<div id="main-left-1">
<%= link_to 'Add List', new_list_path, class: "button", id: "new_link", remote: true %>
</div>
<ul id="lists" data-update-url="<%= sort_lists_url %>">
<% @lists.each do |list| %>
<%= content_tag_for :li, list do %>
<%= link_to list.name, list, :remote => true, :class => "link" %>
<% end %>
<% end %>
</ul>
</div>
<div id="main-right">
</div>
答案 0 :(得分:1)
好吧,我把“item-container”作为ID而不是JS.ERB文件中的类。 SILLY ERRORS!