【发布时间】:2016-06-30 12:18:08
【问题描述】:
我正在从 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 }) %>");
【问题讨论】:
-
您确定调用了 javascript update_price 方法吗?
-
另外,我没有看到 ajax 调用的结果在哪里处理?像一个成功的处理程序?
-
方法肯定被调用了,
.js.erb也应该被format.js调用吧?我将使用该代码更新问题。
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4