使用rails-Ajax调用控制器方法?

时间:2014-03-19 18:27:05

标签: jquery ruby-on-rails ruby ajax

我正在尝试从我视图中的按钮在application_controller.rb中执行Ruby方法。 在昨天的帖子中,有人告诉我使用Ajax调用这样做,因为没有它,只会在页面加载时运行。

我对此非常陌生,我很难理解它。

我安装了rails-Ajax gem,它被添加到我的Gem文件中。

我跟着" Integrate Ajax capabilities to Rails websites with history, bookmarking, partial refreshes, Rails flashes, user callbacks, scripts execution, redirections."直到第5步。

我接下来不知道该怎么做。

这是我目前的配置。该方法仅在页面加载时运行:

我的观点:

<td><button type="button" onclick="executeit()" class="btn btn- default">executer</button></td>

<script>
function executeit() {
 var selectingCommand = document.getElementById("CommandSelect");
 var selectedCommand = selectingCommand.options[selectingCommand.selectedIndex].text;
 var selectingServer = document.getElementById("serverlist");
 var selectedServer = selectingServer.options[selectingServer.selectedIndex].text;
 var username=document.getElementById("login").text;
 var password=document.getElementById("password").text;



<%execute%>;

}
</script>

我在application_controller.rb中的方法:

def execute
  require 'rubygems'
  require 'net/ssh'

  @hostname = "smtlmon02"
  @username = "test"
  @password = "1234"
  @cmd = "ls -al"
  @cmd2 = "sudo su - -c 'ls;date'"
  @cmd3 = "ls -alrt"

  ssh = Net::SSH.start(@hostname, @username, :password => @password)
  res = ssh.exec!(@cmd)
  res2 = ssh.exec!(@cmd2)

  ssh.close
  puts res2

end

如果有人能解释如何做到这一点会很棒!

2 个答案:

答案 0 :(得分:9)

我不确定我是否完全看到了你的目标,但是,如果你只想在点击按钮时调用控制器动作,我会这样做:

这里的HTML:

<a href='#' id='executer-button' class='btn btn-default'>Executer</a>

您应该将其放在app/assets/javascripts/execute_caller.js

//This function calls the "execute" controller action, using its route and also
//passes a "selectingCommand" variable to it
var callExecuter=function(){
  $.ajax({
    type:'GET',
    url:'/executer_route',
    data: { selectingCommand : document.getElementById("CommandSelect"); 
          },
    success:function(){
      //I assume you want to do something on controller action execution success?
      $(this).addClass('done');
    }
  });
}

$(document).on("click","#executer-button",callExecuter);

然后:

  1. 检查您的rake routes,了解哪个是适合控制器操作execute的路线。
  2. 将其替换为url功能的$.ajax(...)字段。
  3. 假设您有debuggerpry gem,请在debugger动作控制器中写下def execute,以确保通过ajax到达那里。
  4. 相应地在ajax调用中编辑您的success操作,这样就可以执行您想要的操作。

答案 1 :(得分:0)

如果您使用的是jQuery,可以添加:

$("button").on("click", function(){
    $.ajax({
        url: "test.html",
        context: document.body
    }).done(
        function() {
            $( this ).addClass( "done" );
        }
    );
});
相关问题