我试图从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
解决方法
男人,你错过了阻止的争论.主要错误.
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
原文地址:https://www.jb51.cc/ruby/268553.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。