我正在尝试从 Rails 3.2 应用程序中的控制器调用 javascript 函数(实际上是 coffeescript).
I'm trying to call a javascript function (actually coffeescript) from a controller in a Rails 3.2 app.
我收到一个在此操作中多次调用渲染和/或重定向错误.
我的代码如下所示:
#Model.controller def index @models = Model.all my_action if current_user.name == "Bob" #or some other general conditional ...and some stuff respond_to do |format| format.html format.js #this is needed to handle ajaxified pagination end end def my_action respond_to do |format| format.js { render :js => "my_function();" } #this is the second time format.js has been called in this controller! end end #functions.js.coffee.erb window.my_function = -> i = xy return something_amazing从控制器调用js函数的正确方法是什么?
What is the correct way to call a js function from the controller?
推荐答案伙计,你错过了块的参数.主要错误.
Man, you missed argument for block. Primary mistake.
def my_action #respond_to do # This line should be respond_to do |format| format.js { render :js => "my_function();" } end endYoshiji 先生的观点是对的.但是你的错误是在服务器端,还没有到达客户端.
And MrYoshiji's point is right. But your error was on server side, had not reached client side yet.
风格方面,我觉得如果js代码只有一个函数调用就好了.如果js代码比较多,最好渲染js模板
For the style, I think that's okay if the js code is one function call only. If more JS code, it's better to render js template
# controller format.js # app/views/my_controller/my_action.js.erb my_function(); // and some more functions.更新:如何解决双重渲染问题
Update: How to fix double rendering problem
如果条件满足,您必须让 #index 返回,否则该方法将继续执行并导致渲染两次或更多次.像这样修复它:
You must have your #index return if condition met, or the method will continue to execute and cause rendering twice or more. Fix it like this:
def index @models = Model.all if current_user.name == "Bob" return my_action else # ...and some stuff respond_to do |format| format.html format.js #this is needed to handle ajaxified pagination end end更多推荐
如何从 Rails 中的控制器调用 javascript 函数
发布评论