我正在尝试从视图中的按钮执行 application_controller.rb 中的 Ruby 方法。
在昨天的一篇文章中,有人告诉我使用 Ajax 调用来执行此操作,因为如果没有它,只会在页面加载时运行。
我对此很陌生,很难理解它。
我安装了rails-Ajax gem,并将其添加到我的Gem 文件中。
我跟着 ”将 Ajax 功能集成到 Rails 网站,包括历史记录、书签、部分刷新、Rails 闪烁、用户回调、脚本执行、重定向。 http://rails-ajax.sourceforge.net/wiki/index.php/Main_Page“直到第 5 步。
我只是不知道下一步该做什么。
这是我当前的配置。该方法仅在页面加载时运行:
My view:
<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
如果有人能解释如何做到这一点,那就太棒了!
我不确定我完全明白你的目标,但是,如果你只想在单击按钮时调用控制器操作,我会这样处理:
这里是 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);
Then:
- 检查你的
rake routes
查看哪个是控制器操作的适当路径execute
.
- 将其替换为
url
的领域$.ajax(...)
功能。
- 假设你有
debugger
or pry
宝石,写debugger
在你的里面def execute
动作控制器,以确保您通过 ajax 到达那里。
- 编辑您的
success
ajax 调用中的操作会相应进行,因此它会执行您希望它执行的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)