Javascript 如何使用ajax将属性从jQuery传递到Rails
我正在尝试使用jQuery(Javascript 如何使用ajax将属性从jQuery传递到Rails,javascript,jquery,ruby-on-rails,ajax,Javascript,Jquery,Ruby On Rails,Ajax,我正在尝试使用jQuery($.ajax)实现Rails3.2拖放购物车 问题: 我不知道如何在JavaScript中传递我的行项目控制器a:product\u id选项。我相信Ajax是关键,所以这就是我现在的想法。目前,使用嵌入ruby的按钮可以轻松地在HTML中实现这一点,如下所示: (<%= button_to('Add to Cart', line_items_path(:product_id => product), :remote => true) %>)
$.ajax
)实现Rails3.2拖放购物车
问题:
我不知道如何在JavaScript中传递我的行项目控制器a:product\u id
选项。我相信Ajax是关键,所以这就是我现在的想法。目前,使用嵌入ruby的按钮可以轻松地在HTML中实现这一点,如下所示:
(<%= button_to('Add to Cart', line_items_path(:product_id => product), :remote => true) %>)
我的HTML:
()
产品),:远程=>true)%>
我的Javascript:
# 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
$(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)) %>"
});
}
});
...
$(文档).ready(函数(){
//结束导航按钮
var dragDrop;
$('.entry')。可拖动({
回复:对,
持续时间:500,
遏制:“文件”,
zIndex:100,
助手:“克隆”,
开始:函数(){
dragDrop=$(this).data('id');
}
});
$(“#购物车”)。可拖放({
接受:'.entry',
activeClass:'活动',
hoverClass:“悬停”,
drop:函数(事件、用户界面){
美元邮政({
url:“产品”)%>“
});
}
});
...
到目前为止,除了没有:product\u id
传递到line\u items
之外,拖拽和拖拽都是有效的。当我拖拽一个项目时,我只是在我的命令控制台中得到了错误错误URI'/store/[object object].
。post函数应该是:
$.post({
url: "<%= escape_javascript(line_items_path(:product_id => product.id)) %>"
});
$.post({
url:“product.id))%>”
});
注意product.id
而不是product
Hmm,我进行了切换,但仍然得到“错误错误URI/store/[object%20Object]“错误。那么问题可能出在我的路由上了吗?为什么需要调用“/store/…”呢?我的路由确认后,line_items_path不是发布到“/line_items”吗?谢谢,我找到了答案。我没有转义到rails,而是使用了以下ajax:$.ajax({type:“post”,url:“/line_items?”),beforeSend:function(xhr){xhr.setRequestHeader('X-CSRF-Token',$('meta[name=“CSRF-Token”]).attr('content'))},数据:{product_id:dragDrop,remote:true},数据类型:“script”});
$.post({
url: "<%= escape_javascript(line_items_path(:product_id => product.id)) %>"
});