我已开始使用rails,我试图从rails控制器调用javascript 结构如下
app/controllers/
hello_controller.rb
def search
//calling show.js.erb
end
app/views/hello/show.js.erb
基本上我想从javascript调用html文件(div标签)
The point is i want to do nothing when the page is opened , but to run the javascript when show button is hit
同一点 - 在控制器中写入
respond_to do |format|
format.html{
}
format.js{ render template: 'show', layout: false }
end
并在show.js.erb中写道 警报( “你好”);
不工作!
答案 0 :(得分:0)
class HelloController < ApplicationController
def search
respond_to do |format|
format.js{ render template: 'show', layout: false }
end
end
end
答案 1 :(得分:0)
最简单的方法如下:
def search
@var = Model.where(name: params[:search]) # will be available in search.js.erb
respond_to :js # will try to render search.js.erb in views/hello/
end
您可以渲染自定义js文件:
def search
# some code..
respond_to :js { render 'show' }
end
答案 2 :(得分:0)
将类似的代码放入您的应用程序套件中
respond_to do |format|
format.js # actually means: if the client ask for js -> return file.js
end