在Rails控制器中调用JavaScript函数是否可能?
我的做法是让一个Rails控制器生成一个javascript动作。我让它调用一个包含javascript的局部视图。
除非你想在页面加载时激活它,否则我会通过AJAX设置它。这样我就可以向控制器发出AJAX调用,然后调用一个javascript文件。
这可以通过投票来看到:
首先是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();
其次是控制器
被点击的类$(".vote")
具有一个 href 属性,可以调用到我的控制器。
def vote_up
respond_to do |format|
# The action 'vote' is called here.
format.js { render :action => "vote", :layout => false }
end
end
现在控制器加载了一个AJAX文件
// this file is called vote.js.haml
== $("#post_#{@post.id}").replaceWith("#{ escape_javascript(render :partial => 'main/post_view', :locals => {:post_view => @post}) }");
你已经成功地从控制器调用了一个 JavaScript 函数。
def vote
的@post
..等等。 - Tripremote: true
,以便在单击时调用 js 而不是呈现新页面。 - mpgarate不行,但你可以输出JavaScript代码,在视图中立即调用它,例如:
<script type="text/javascript">
function IWillBeCalledImmediately()
{
alert('called');
};
IWillBeCalledImmediately();
</script>
然而,最好使用jQuery并使用ready事件。
<script type="text/javascript">
$(function() {
alert('called');
});
</script>