将数据从JS发送到Rails

时间:2019-04-25 11:40:05

标签: javascript ruby-on-rails model-view-controller

我的项目中控制器上有一个变量。 我想将变量从控制器发送到js, 变量在js上再次计算,并从js发送到控制器。但我失败了。我该怎么做?从现在开始谢谢你。

  %input#calculate{ type: 'text', value: "#{@cpp}", disabled: true }/

@cpp变量发送到js。它再次计算。在屏幕上打印新值。但是@cpp值不变。

1 个答案:

答案 0 :(得分:0)

view / calculation.html.haml

.container
  .calculator
    .calculator__display
      %input#calculate{ type: 'text', value: "#{@cpp}", disabled: true }/
    .calculator__keys
      %input{ onclick: 'nine()', type: 'button', value: '9' }/
      %input{ onclick: 'eight()', type: 'button', value: '8' }/
  .dropdown.position-right
    %button.btn.none-focus
      = '='
      .dropdown-content
        = link_to user_calculations_path(operation_type: "=",  calculate_piece_price: @cpp),                                                   
                method: :post,
                class: 'button btn btn-info' do
          = t('view.btn.calculation')

资产/javascipts/application.js

function nine(){
    var calculate =  document.getElementById("calculate");
    if (calculate.value == "0") {
        calculate.value =  "9" ;
    }
    else {
        calculate.value = calculate.value + "9";
    }
}

function eight(){
    var calculate =  document.getElementById("calculate");
    if (calculate.value == "0") {
        calculate.value =  "8" ;
    }
    else {
        calculate.value = calculate.value + "8";
    }
}

controller / calculations_controller.rb

  def calculation_piece_payment
    @cpp = Calculation.quantity.to_s
  end