[英]How to add some ajax to shopping cart in rails?
我只想簡單地說:當輸入值更改時,我會將這個值放在db中。 我想添加一些ajax。 我想這樣做:當我更改輸入值(聚焦)時,我使用get-parametr調用了一些方法,我的方法如下所示:
def update_quantity
@cart = current_cart
@line_item = LineItem.find(params[:id])
respond_to do |format|
if @line_item.update_attribute(:quantity, params[:quantity]) #&& @cart.id == params[:cart]
format.html { redirect_to(@line_item, :notice => 'Line item was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity }
end
end
end
這是測試工作,因此可能有一些不好的解決方案,我的看法如下所示:
%p
= line_item.art_name
= line_item.ART_ID
= line_item.art_code
×
.cart-quantity
= line_item.quantity
%input{ :class => "quantity", :value => line_item.quantity }
= link_to "обновить", :controller => "line_items", :action => "update_quantity", :id => line_item.id, :quantity => line_item.quantity, :cart => @cart.id
= line_item.total_price
如您所見,我想:當輸入焦點不在時,我得到一個新的隱藏鏈接,並調用它,它調用上面寫的方法。 我需要做什么? 創建哪些文件以及在何處創建文件,以及如何執行此操作? 想要一些ajax)
我只想簡單地說:當輸入值更改時,我會將這個值放在db中。
您不需要隱藏鏈接即可完成此操作。 使用html元素的onblur字段:
:javascript
function updateQuantity() {
$.ajax({
url: "/line_items/update_quantity",
type: "POST",
data: {id: $(this).attr('id'), quantity: $(this).attr('quantity'), cart: $(this).attr('cart_id')}
})
}
%input.quantity{:value => line_item.quantity, :onblur => updateQuantity(); :id => line_item.id, :quantity => line_item.quantity, :cart => @cart.id}
在此示例中,我內聯了javascript,它實際上應該放在您的application.js document.ready()塊中
$(document).ready(function() {
$(".quantity").onfocusout(function() {
$.ajax({
url: "/line_items/update_quantity",
type: "POST",
data: {id: $(this).attr('id'), quantity: $(this).attr('quantity'), cart: $(this).attr('cart_id')}
})
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.