如何从 Rails 中的控制器调用 javascript 函数

编程入门 行业动态 更新时间:2024-10-09 09:21:09
本文介绍了如何从 Rails 中的控制器调用 javascript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从 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 end

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

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 函数

本文发布于:2023-11-17 11:02:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609806.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   函数   Rails   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!