簡體   English   中英

Rails:遠程:從select_tag為true

[英]Rails: remote: true from select_tag

我正在從select_tag調用AJAX函數, select_tag所示:

<%= 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在任何地方都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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM