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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16697333/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:01:47  来源:igfitidea点击:

how to call javascript functions from the controller in rails

ruby-on-rails

提问by Andy Harvey

I'm trying to call a javascript function (actually coffeescript) from a controller in a Rails 3.2 app.

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

I'm getting a Render and/or redirect were called multiple times in this actionerror.

我收到一个Render and/or redirect were called multiple times in this action错误。

My code looks like this:

我的代码如下所示:

#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

What is the correct way to call a js function from the controller?

从控制器调用 js 函数的正确方法是什么?

回答by Billy Chan

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
end

And MrYoshiji's point is right. But your error was on server side, had not reached client side yet.

吉二先生的观点是对的。但是你的错误是在服务器端,还没有到达客户端。

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

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

 # controller
 format.js

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

Update: How to fix double rendering problem

更新:如何解决双重渲染问题

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:

如果条件满足,您必须让 #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