我从select_tag
调用AJAX函数,如此:
<%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %>
以下是功能:
<script type='text/javascript'>
function update_price(order_id, quantity) {
$.ajax({
url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
type: "POST",
data: {
"order_id" : order_id,
"quantity" : quantity },
dataType: "html"
});
}
</script>
我的.js.erb
永远不会被打电话,我怀疑它是因为我还没有在任何地方指定remote: true
,但因为我没有形式本身我不知道如何做到这一点。有什么帮助吗?
此处的相关控制器代码:
class CartTransactionsController < ApplicationController
load_and_authorize_resource
respond_to :html, :js
before_filter :set_cart_transaction
def update_quantity
@order = @cart_transaction.orders.find(params[:order_id])
@price = current_user.brand.prices
.where(template_id: @order.document.template.id)
.where(quantity: params[:quantity]).first
@order.update_attributes(
price_cents: @price.amount_cents, quantity: params[:quantity]
)
@cart_transaction.save!
respond_to { |format| format.js }
end
private
def set_cart_transaction
@cart_transaction = current_user.cart
end
def cart_transactions_params
params.require(:cart_transaction).permit(
:name, :email, :delivery_address, :comments
)
end
end
更新
以下是由于某种原因未被调用的.js.erb
:
console.log("update_quantity.js.erb file");
$('#price_cell').html("<%= j render(partial: 'price', locals: { order: @order }) %>");
$('#subtotals').html("<%= j render(partial: 'subtotals', locals: { cart_transaction: @cart_transaction }) %>");
答案 0 :(得分:2)
试试这个:
function update_price(order_id, quantity) {
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
type: "POST",
data: {
"order_id" : order_id,
"quantity" : quantity }
});
}
答案 1 :(得分:0)
使用dataType:“script”,它将起作用并将呈现js.erb