从控制器调用javascript函数
是否可以从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函数。
不,但您可以输出将在您的视图中立即调用的javascript,例如
但是,使用jquery并使用ready事件可能会更好。