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

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

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

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

我遵循“ 将Rax网站的Ajaxfunction集成到历史记录,书签,部分刷新,Rails闪存,用户回调,脚本执行,重定向。 ”直到第5步。

我只是不知道接下来要做什么。

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

我的看法:

  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; ; }  

我在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 

如果有人能解释如何做到这一点真是太棒了!

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

这里是HTML:

 Executer 

你应该把它放在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. 将其替换为$.ajax(...)函数的url字段。
  3. 假设您有debuggerpry gem,请在def execute操作控制器中编写debugger ,以确保通过ajax到达那里。
  4. 相应地在ajax调用中编辑on success操作,这样它就可以完成您想要的操作。

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

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