如何在Javascript函数中使用Ruby传递html值

How to pass html values in Ruby within a Javascript function

本文关键字:Ruby 传递 html Javascript 函数      更新时间:2023-09-26

我有一个视图页面,其中用户输入一个数字并单击generate以在同一页面中基于此输入获取表单。我在主视图中使用javascript:

 <div class="label-field-pair"><%= "#{t('total')} #{t('amount')}" %>:
    <%= form.text_field :total, :value =>precision_label(@total_pay.to_f)  , :disabled=> true , :id=>'total' %></div>

      <div class="label-field-pair">
        <label for="student_grade"><%= t('no_payments') %><span class="necessary-field">*</span> </label>
        <input type="number" min="1" max="12" step="1" value="1" name="no_payments" id="no_payments">      </div>
       <%= form.hidden_field :no_payments, :id=>'payments' %>
       <%= form.hidden_field :total_pay, :id=>'total_pay' %>
    <%#= submit_tag "", :value => "► #{t('generate')}", :class => "submit_button", :disable_with => "► #{t('please_wait')}" %>
    <%#= render :partial => 'distribute_payments', :locals => {:no_payments=>2, :total => 30000 , :guardian=>@guardian.id} %>
    <button type="button" id="gen" onClick="generate()" style="display: block">Generate</button>
    <div id="payments_distribute"></div>
   <%end%>

  <script type="text/javascript">
       function generate() {

          var t = document.getElementById("total").value;
          var n = document.getElementById("no_payments").value;
          j('#total_pay').val("<%= @total_pay %>");
         document.getElementById("gen").style.display = "none";
          <%="#{remote_function(:url => {:action => "distribute_payments", :id=>@guardian.id,:total_pay=>@total_pay}
          )}"%>
      }

  </script>

这是我的局部视图的动作:

  def distribute_payments
    @total_amount=params[:total]
      @no_payments=params[:no_payments]
      @total_payment=params[:total_pay]
     @guardian = Guardian.find(params[:id])
    @students=Student.find_all_by_sibling_id(@guardian.ward_id)
      render(:update) do |page|
            page.replace_html 'payments_distribute', :partial=>'distribute_payments', :total_pay=>@total_payment, :no_payments=>@no_payments
         end
  end

这里的问题是,我需要将"no_payments"的值与参数传递给我的局部视图,我不知道如何从我的Javascript函数(remote_function)中做到这一点。我试图使用render_partial与提交按钮,但我不能打开局部视图在同一页面。你可以检查我的问题在这里:Rails:渲染部分从控制器

您需要使用Ajax:

  <script type="text/javascript">
       function generate() {

          var t = document.getElementById("total").value;
          var n = document.getElementById("no_payments").value;
          var id="<%= @guardian.id %>"
          j('#total_pay').val("<%= @total_pay %>");
         document.getElementById("gen").style.display = "none";

                 j.ajax({
      type: 'POST' ,
      url: '<%=  url_for :action => "distribute_payments" %>',
      data : {
        'no_payments' :n,
        'total_payment' :t,
        'id' :id
      },
      beforeSend : function() {
      },
      success : function() {
        j("#payments_distribute").html(data)
      }});
      }

  </script>