respond_to do |format|
format.js # actually means: if the client ask for js -> return file.js
end
js
这里指定控制器方法将作为响应发回的 mime 类型;
默认 Rails 哑剧类型。
如果您也尝试使用format.yaml
:
respond_to do |format|
format.js
format.yaml
end
这意味着您的控制器将返回yml
或js
取决于客户端的要求;
{}
对 ruby 而言是一个块;如果您不指定任何 rails 将尝试从 app/views/[contoller name]/[controller method name].[html/js/...] 渲染默认文件
# app/controllers/some_controller.rb
def hello
respond_to do |format|
format.js
end
end
会寻找/app/views/some/hello.js.erb
;// 至少在 Rails v. 2.3 中。
如果您确实指定了块:
respond_to do |format|
# that will mean to send a javascript code to client-side;
format.js { render
# raw javascript to be executed on client-side
"alert('Hello Rails');",
# send HTTP response code on header
:status => 404, # page not found
# load /app/views/your-controller/different_action.js.erb
:action => "different_action",
# send json file with @line_item variable as json
:json => @line_item,
:file => filename,
:text => "OK",
# the :location option to set the HTTP Location header
:location => path_to_controller_method_url(argument)
}
end