问题
I have this code in my store.html.erb file
<%= link_to t('.add_html'), 'javascript:void(0);',
:class => "line-item", :product => product.id %>
<script type="text/javascript">
$('document').ready(function(){
$(".line-item").click(function(){
var prod = $(this).attr('product');
$.ajax({
url:'<%= line_items_url %>',
data: {product_id: prod},
type: 'POST',
dataType: 'script'
});
});
});
</script>
my line_items_controller.rb has this code
def create
@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_url) }
format.js { @current_item = @line_item }
format.xml { render :xml => @line_item,
:status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
And then my create.js.erb file has this code
$("#notice").hide()
$("#cart").html("<%= j render(@cart) %>")
And my _cart.html.erb
<% unless cart.line_items.empty? %>
<div class="cart_title"><%= t('.title') %></div>
<table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %> </td>
</tr>
</table>
<%= button_to t('.checkout'), new_order_path, :method => :get %>
<%= button_to t('.empty'), cart, :method => :delete,
:confirm => "Are you sure?" %>
<% end %>
Now when I click add to cart button products should be added in the cart and this should show the updated value in the left side of page but it is not showing this. But when I refresh the page I see the updated value. That means my javascript is not working. Please let me know why my javascript is not working.
回答1:
Add this line in your create.js.erb file
$("#cart").html("<%= escape_javascript(render(@cart)) %>");
This should work
回答2:
you have to send the @cart
as locals in cart partial and defiantly it will update the value dynamically.
来源:https://stackoverflow.com/questions/20755345/javascript-is-not-working-in-rails-app