Rails: remote: true from select_tag

Rails: remote: true from select_tag

本文关键字:tag select true remote Rails from      更新时间:2023-09-26

我正在从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 }) %>");

试试这个:

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 }
    });
  }

使用dataType: "script",它将工作,并将呈现js.erb