【发布时间】:2015-08-08 04:40:54
【问题描述】:
我到处寻找,但似乎找不到为什么我的 AJAX 请求没有通过将商品添加到购物车的问题。
line_items_controller.rb
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_url }
format.js { @current_item = @line_item }
format.json { render action: 'show',
status: :created, location: @line_item }
else
format.html { render action: 'new' }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
end
存储/index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% @products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
<%= button_to 'Add to Cart', line_items_path(product_id: product),
remote: true %>
</div>
</div>
<% end %>
<% end %>
<% end %>
line_items/create.js.erb
$('#cart').html("<%= escape_javascript render(@cart) %>");
$('#current_item').css({'background-color':'#88ff88'}).
animate({'background-color':'#114411'}, 1000);
line_items/_line_item.html.erb
<% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td> <%= line_item.quantity %>× </td>
<td> <%= line_item.product.title %> </td>
<td class= "item_price" > <%= number_to_currency(line_item.total_price) %> </td>
</tr>
我可以在我的日志文件中看到,每次我将商品添加到购物车时,该页面都会发送一堆 GET 请求,并且我可以看到它重新加载。在日志文件中没有发现错误。
多次重启网站。检查我是否正确安装了 jquery 和 jquery-ui gem。没有任何改变。
【问题讨论】:
标签: jquery ruby-on-rails ajax