使用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);
然后:
- 检查您的
rake routes
以查看哪个是到控制器操作execute
的适当路由。 - 将其替换为
$.ajax(...)
函数的url
字段。 - 假设您有
debugger
或pry
gem,请在def execute
操作控制器中编写debugger
,以确保通过ajax到达那里。 - 相应地在ajax调用中编辑on
success
操作,这样它就可以完成您想要的操作。
如果您使用的是jQuery,可以添加以下内容:
$("button").on("click", function(){ $.ajax({ url: "test.html", context: document.body }).done( function() { $( this ).addClass( "done" ); } ); });
- 如何在进行ajax调用后从控制器呈现部分
- 为什么这个button_to在Rails 3.2.11中呈现错误?
- Rails 3:使用AJAX请求更新URL参数
- 使用will_paginate gem在rails 3.2.3中调用Ajax
- Rails 5.1.2 – form_with未在html中显示data-remote =“true”
- 从多个CKEditor内联编辑器字段中保存数据,如模板
- 使用带远程的ajax的Ruby表单:true给出了ActionController :: InvalidAuthenticityToken错误。 经典提交没有
- Ruby on Rails国家/州选择Enigma
- will_paginate找出我是否在最后一页