[英]Rails - rendering a javascript file
I'm new to Ruby & I'm struggling serving a javascript file and executing it. 我是Ruby的新手,我正在努力提供JavaScript文件并执行它。
I'm trying to build an embeddable widget so when someone runs mydomain.com/widget.js, he will get the javascript file which will execute after fetching it 我正在尝试构建一个可嵌入的小部件,所以当有人运行mydomain.com/widget.js时,他将获得将在获取它后执行的javascript文件
loader.js.erb content: loader.js.erb内容:
(function(global) {
var WIDGET = WIDGET || {};
WIDGET.version = '0.1';
})(this);
router.rb content: router.rb的内容:
get 'widget.js' => 'application#test'
application_controller.rb content: application_controller.rb的内容:
def test
render template: 'loader.js.erb', status: :ok, content_type:'text/javascript'
end
I'm expecting after calling for mydomain.com/widget.js, to see WIDGET in the global object, but at the moment it renders it as HTML 我期望在调用mydomain.com/widget.js之后,在全局对象中看到WIDGET,但目前它会将其呈现为HTML
Try this: 尝试这个:
Create a before filter and make changes in request format: 创建一个before过滤器并以请求格式进行更改:
before_filter :set_js_request_format
def set_js_request_format
request.format = :js
end
Hope it is helpful for you. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.