2014-03-19 24 views
1

我想从我的视图中的按钮在我的application_controller.rb中执行Ruby方法。 在昨天的一篇文章中,有人告诉我使用Ajax调用来这样做,因为没有它,就会在页面加载时运行。使用rails-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 

这将是美妙的,如果任何人都可以解释如何做到这一点!

回答

8

我不知道我完全看你的目标,但是,如果你只是想在你的按钮,点击时要调用一个控制器动作,我将接近这样的:

这里的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. 将其替换为$.ajax(...)函数的url字段。
  3. 假设您有debuggerpry宝石,请在您的def execute动作控制器中写入debugger,以确保您通过ajax到达那里。
  4. 相应地在ajax调用中编辑您的success操作,以便它按照您的要求执行操作。
+0

谢谢我做到了! –

+0

'data:'-line是做什么的?有必要吗?我正在研究一个非常类似的问题。 – user3383458

+0

我可以以某种方式将信息传递给它吗?像'this.getAttribute('w_id');' – user3383458

0

如果您正在使用jQuery,你可以补充一点:

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

我可以问一下在哪个文件中我必须使用这段代码吗? :) –

+0

我会猜这里,纠正我,如果我错了: 我需要用我的按钮的ID替换“按钮”。 我需要用我的方法名称替换function():“execute” 而且我需要用我的视图名称替换test.html:“test.html.erb” ? –

+0

嗨, 我似乎无法超越如何使其工作.. 你能解释一点点吗? –