Rails的checkbox_tag与阿贾克斯Rails、checkbox_tag、阿贾克斯

2023-09-11 00:41:41 作者:从小缺根筋

我试图找出如何传递的Rails 3.2.11使用复选框使用Ajax的数据。我有以下线在我看来

I'm trying to figure out how to pass data with ajax using a checkbox in Rails 3.2.11. I have the following line in my view

<%= check_box_tag(
        "institution_ids_#{inst.name.gsub(" ", "")}",
          inst.id,
          false,
        data: {
          remote: true,
          institution_id: inst.id}) %>

当我改变复选框的状态,我可以看到,该控制器正确获取调用(控制器,这正是我想要的,因为这是我在考虑具体的指标法),但是,我似乎无法从控制器上params哈希表访问institution_id变量。有人可以解释我是如何使用Ajax从视图中的复选框内的控制器传递数据。我想远程:真正的函数将正确地调用控制器(这是做),与我设置的其他参数(它没有)

When I change the status of the checkbox, I can see that the controller is correctly getting called (specifically the index method of the controller, which is what I want as that is the view I'm in), however, I cannot seem to access the institution_id variable from the params hash on the controller. Can someone please explain how I use ajax to pass data from the view to the controller within a checkbox. I thought the remote: true function would correctly call the controller (which is does) with the additional parameters that I set (which it doesn't).

推荐答案

你为什么不使用jQuery做阿贾克斯电话。

Why don't you use jquery to make Ajax call.

<%= check_box_tag( "institution_ids_#{inst.name.gsub(" ", "")}", inst.id, false %>

<script>
     $('#checkbox_id').change(function(){
        $.get('controller/action?inst_id='+$(this).val(), function(data,status){
            if(status == 'success'){
              alert(data)
             }
        })
     })
   </script>

在控制器:

def action
   inst_id = params[:inst_id]
   #do something
   render :text => "success" 
end