我正尝试通过我 View 中的按钮在我的 application_controller.rb 中执行一个 Ruby 方法。 在昨天的帖子中,有人告诉我使用 Ajax 调用来执行此操作,因为没有它,只会在页面加载时运行。
我对此很陌生,很难理解。
我安装了 rails-Ajax gem,它被添加到我的 Gem 文件中。
我只是不知道下一步该怎么做。
这是我当前的配置。该方法仅在页面加载时运行:
我的看法:
<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
如果有人能解释如何做到这一点,那就太好了!
最佳答案
我不确定我是否完全理解您的目标,但是,如果您只想在单击按钮时调用 Controller 操作,我会这样处理:
这里是 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);
然后:
- 检查您的
rake routes
以查看哪个是 Controller 操作execute
的合适路径。 - 将其替换到
$.ajax(...)
函数的url
字段中。 - 假设您有
debugger
或pry
gem,在您的def execute
Action Controller 中写入debugger
,以确保您通过 ajax 到达那里。 - 相应地在 ajax 调用中编辑您的 on
success
操作,使其执行您希望它执行的操作。
关于jquery - 使用 rails-Ajax 调用 Controller 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514956/