简体   繁体   English

将数据从视图发送到Rails中的控制器

[英]send data from view to controller in rails

I want to send some data from view to controller in rails through ajax. 我想通过Ajax从视图向Rails中的控制器发送一些数据。

I have the following code in app/view/static/home.html.erb 我在app / view / static / home.html.erb中有以下代码

 <script type="text/javascript">
        var dummy = "testtext";
        $('#finish').click(function() {
          $.ajax( {
            url: '/finish',
            type: 'POST',
            data: dummy,
            dataType: 'text'
          });
         });
      </script>

      <body>
        <%= button_to "Finish", {:action => 'finish', :controller => 'static'}, :method => :post, id => 'finish' %>
      </body>

in app/view/static/finish.html.erb 在app / view / static / finish.html.erb中

<p><%= @data %></p>

app/controller/static_controller.rb app / controller / static_controller.rb

def finish
@data = params[:data]
end

in routes.rb 在routes.rb中

post 'finish' => 'static#finish'

My understanding is that on button click the ajax script will be executed and rails action will store the data passed from view. 我的理解是,单击按钮后,将执行ajax脚本,并且rails动作将存储从视图传递的数据。 This doesn't seem to work. 这似乎不起作用。 I'm not sure if my understanding of the flow is right. 我不确定我对流程的理解是否正确。

Because you are calling params[:data] in the controller, you need to specify that {data: dummy} in the AJAX data section 因为您要在控制器中调用params [:data],所以需要在AJAX数据部分中指定{data:dummy}

<script type="text/javascript">
    var dummy = "testtext";
    $('#finish').click(function() {
      $.ajax( {
        url: '/finish',
        type: 'POST',
        data: {data: dummy},
        dataType: 'text'
      });
     });
  </script>

Also you might want to respond to your AJAX call in your controller using the following 另外,您可能想使用以下命令在控制器中响应AJAX调用

def finish
  @data = params[:data]
  respond_to do |format|
    format.json { insert_your_code_here }
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM