2014-03-19 48 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

嗨, 我似乎無法超越如何使其工作.. 你能解釋一點點嗎? –