[英]How to pass attributes from jQuery to Rails using ajax
I'm trying to implement a Rails 3.2 drag and drop shopping cart using jQuery ( $.ajax
). 我正在尝试使用jQuery( $.ajax
)实现Rails 3.2拖放购物车。
Problem: I can't figure out how to pass my line_items
controller a :product_id
option in JavaScript. 问题:我不知道如何在JavaScript line_items
控制器传递给:product_id
选项。 I believe Ajax is the key, so that's where my heads at right now. 我相信Ajax是关键,所以这就是我现在要面对的地方。 Currently, this is easily done in HTML using a button_to
with embedded ruby like so: 目前,使用带有嵌入式红宝石的button_to
在HTML中可以轻松完成此操作,如下所示:
(<%= button_to('Add to Cart', line_items_path(:product_id => product), :remote => true) %>)
However to implement the drag/drop function, the above action needs to be triggered upon a drop
. 然而,为了实现拖动/降功能,上述动作需要在一个被触发drop
。 How can this be done in JavaScript? 如何用JavaScript完成?
My controller: 我的控制器:
# POST /line_items
# POST /line_items.json
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_index_url) }
format.js { @current_item = @line_item }
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
My HTML: 我的HTML:
<% @products.each do |product| %>
<div class="entry" data-id="<%= product.id %>">
<h3><%= product.title %> </h3>
<%= image_tag(product.image_url)%>
<div style="display: none; width: 10px"><%= sanitize(product.description) %> </div>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>(<%= product.unit_of_measure%>)
<br>
<%= button_to('Add to Cart', line_items_path(:product_id => product), :remote => true) %>
</div>
</div>
<p>
<% end %>
My Javascript: 我的Javascript:
$(document).ready(function(){
//End Navigation Buttons
var dragDrop;
$('.entry').draggable({
revert: true ,
revertDuration: 500,
containment: "document",
zIndex: 100,
helper: "clone",
start: function(){
dragDrop = $(this).data('id');
}
});
$('#cart').droppable({
accept: '.entry',
activeClass: 'active',
hoverClass: 'hovered',
drop: function( event, ui ){
$.post({
url: "<%= escape_javascript(line_items_path(:product_id => product)) %>"
});
}
});
...
So far the drag works and the drop works except there is no :product_id
passed to line_items
. 到目前为止,除了没有:product_id
传递给line_items
以外,拖动有效并且拖放有效。 I just get ERROR bad URI '/store/[object Object]'.
我只是得到ERROR bad URI '/store/[object Object]'.
in my command console when I drop an item. 在我放下项目时在命令控制台中。
The post function should be: 发布功能应为:
$.post({
url: "<%= escape_javascript(line_items_path(:product_id => product.id)) %>"
});
Note product.id
instead of product
注意product.id
而不是product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.