Calling javascript functions from controller
Is it possible to call a javasc开发者_JS百科ript function from a controller in rails?
What I do is to make a Rails controller produce a javascript action. Is have it call a partial that has javascript included in it.
Unless you want that activated on page load, I would set it up via AJAX. So that I make an AJAX call to the controller which then calls a javascript file.
This can be seen via voting :
First the AJAX
//This instantiates a function you may use several times.
jQuery.fn.submitWithAjax = function() {
this.live("click", function() {
$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
return false;
});
};
// Here's an example of the class that will be 'clicked'
$(".vote").submitWithAjax();
Second the Controller
The class $(".vote")
that was clicked had an attribute href that called to my controller.
def vote_up
respond_to do |format|
# The action 'vote' is called here.
format.js { render :action => "vote", :layout => false }
end
end
Now the controller loads an AJAX file
// this file is called vote.js.haml
== $("#post_#{@post.id}").replaceWith("#{ escape_javascript(render :partial => 'main/post_view', :locals => {:post_view => @post}) }");
You have successfully called a javascript function from a controller.
No, but you could output javascript that would be called immediately in your view e.g.
<script type="text/javascript">
function IWillBeCalledImmediately()
{
alert('called');
};
IWillBeCalledImmediately();
</script>
However it would probably be better to use jquery and use the ready event.
<script type="text/javascript">
$(function() {
alert('called');
});
</script>
精彩评论