从控制器调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5017114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling javascript functions from controller
提问by ssri
Is it possible to call a javascript function from a controller in rails?
是否可以从 Rails 中的控制器调用 javascript 函数?
回答by Trip
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.
我所做的是让 Rails 控制器产生一个 javascript 动作。它是否调用了包含 javascript 的部分。
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.
除非你想在页面加载时激活它,否则我会通过 AJAX 设置它。这样我就对控制器进行了 AJAX 调用,然后控制器调用了一个 javascript 文件。
This can be seen via voting :
这可以通过投票看到:
First the AJAX
首先是 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.
$(".vote")单击的类有一个属性 href 调用我的控制器。
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
现在控制器加载一个 AJAX 文件
// 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.
您已成功从控制器调用了 javascript 函数。
回答by Rob Stevenson-Leggett
No, but you could output javascript that would be called immediately in your view e.g.
不,但您可以输出将在您的视图中立即调用的 javascript,例如
<script type="text/javascript">
function IWillBeCalledImmediately()
{
alert('called');
};
IWillBeCalledImmediately();
</script>
However it would probably be better to use jquery and use the ready event.
但是,使用 jquery 并使用 ready 事件可能会更好。
<script type="text/javascript">
$(function() {
alert('called');
});
</script>

