I've got a list of servers with their names and the status of whether they are up or not by pinging them.
However, because there are 2-300 different servers, it t开发者_如何转开发akes a while for the Ping requests to complete and display the page, hence I want to improve it by using a button which the user clicks, which then opens up an alert box informing the user whether the server is Up and running or not.
I've already got a ruby method to do the testing, however when I do
<%= button_to_function "Status", "alert(serverUp?)" %>
the button on my form doesn't do anything. Is it because it only recognises JS as the action? Would really like to get some help with it.
Otherwise, if anyone has any better idea of displaying the main page quickly, and then asynchronously run the serverUp?
method so that the results are dynamically displayed in the table and it doesn't slow the page down to be displayed, I'd be grateful.
Thanks a lot in advance.
No, you can't run Ruby code onclick
. Think of it like this: your app handles the browser's request, runs the controller, interpolates the Ruby into the .erb
view file - producing plain text - and then sends that back over the wire to the browser. The browser has no idea what your server is running; it just interprets the onclick
event as Javascript to be run.
If you want to asynchronously load the results into a pre-displayed table, you definitely can. Set up a controller action which runs the ping and returns the result (in text format), and have the onclick
of the button (or a script run on load of the page) call that method. You should be able to use link_to :remote => true
(or link_to_remote
for Rails 2.x) - check your documentation.
Assuming that serverup?
method works fine you might assign its result to some instance variable in controller and later use it in view as following
<%= button_to_function "Status", "alert('#{some_var}')" %>
Edit or without rails helpers
<input type="button" value="submit" onclick=<%= "alert('#{@var}')" %>>
however it's value should mot include any '
otherwise escape_javascript
helper also have to be used
if you want update it with AJAX it might be sth like
$('#my_button').click(function() {
$.post('/server_status/1', {}, function(response) {
alert(response);
}
});
精彩评论