简体   繁体   中英

Rails - rendering a javascript file

I'm new to Ruby & I'm struggling serving a javascript file and executing it.

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

loader.js.erb content:

(function(global) {
  var WIDGET = WIDGET || {};

  WIDGET.version = '0.1';
})(this);

router.rb content:

get 'widget.js' => 'application#test'

application_controller.rb content:

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

Try this:

Create a before filter and make changes in request format:

before_filter :set_js_request_format

def set_js_request_format
  request.format = :js
end 

Hope it is helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM