瀏覽器我這傢伙Ajax請求不能看到效果,而刷新的Rails
我改變RJS到js.erb就像他所面臨的same problem。我們都使用<%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>
向控制器發送AJAX請求。 format.js
罰款並執行create.js.erb。但購物車沒有添加任何東西。
日誌結果:
Rendered line_items/_line_item.html.erb (4.3ms) Rendered carts/_cart.html.erb (8.0ms) Rendered line_items/create.js.erb (8.8ms)
那是index.html.erb我們發送AJAX請求
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
<div class="entry">
<%= link_to image_tag(product.image_url), line_items_path(:product_id => product), html_options = {:method => :post} %>
<h3><%= product.title %></h3>
<%=sanitize product.description %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price,:precision=>3) %></span>
<%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>
</div>
</div>
<% end %>
這就是line_items控制器功能來處理請求
# POST /line_items
# POST /line_items.json
def create
# for exercise only
session[:counter] = nil
@cart = current_cart
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_index_path }
format.js
format.json { render json: @line_item, status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
create.js.erb
$('#cart').html("<%= escape_javascript(render(@cart)) %>");
您需要添加更多信息。沒有足夠的信息可以幫助我們。 –
您的視圖文件夾中是否有'create.js.erb'文件?當您請求.js(AJAX)響應時,Rails需要知道應該向您回饋什麼。 – Zajn
我在裏面有一個'create.js.erb'。問題似乎是,沒有從'index.html.erb'發送到控制器的AJAX請求,所以'format'總是'format.html' – code4j