ruby-on-rails – 如何从rails中的控制器调用javascript函数

我试图从Rails 3.2应用程序中的控制器调用 javascript函数(实际上是coffeescript).

在这个操作错误中多次调用渲染和/或重定向.

我的代码如下所示:

#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函数的正确方法是什么?

解决方法

男人,你错过了阻止的争论.主要错误.
def my_action
  #respond_to do # This line should be
  respond_to do |format|
    format.js { render :js => "my_function();" }
  end
end

而且,Yoshiji先生的观点是正确的.但是你的错误是在服务器端,还没有到达客户端.

对于样式,我认为如果js代码只是一个函数调用就可以了.如果有更多JS代码,最好渲染js模板

# controller
 format.js

 # app/views/my_controller/my_action.js.erb
 my_function();
 // and some more functions.

更新:如何修复双重渲染问题

如果满足条件,则必须返回#index,否则方法将继续执行并导致渲染两次或更多次.修复如下:

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...