Rails 4 - force browser to execute javascript response instead of displaying text

大兔子大兔子 提交于 2021-02-07 19:41:21

问题


I have a Rails 4 application where I need to force the controller to send a js response to all requests, html or js. For some reason, the browser is displaying the response as text instead of executing the code when the controller receives an html request (for example, when the user makes a request by typing in the url).

Controller:

def action
  render :template => 'sessions/home.js.erb', :content_type => "text/javascript"
end

sessions/home.js.erb:

$("#button").on("click", function(){
  alert("got here");
});

Instead of binding #button, the browser simply displays the code from home.js.erb as text.

I've tried the following options in the controller but the results are the same - the browser just presents the text vs executing the code:

render js: "alert('got here')";

or

render :format => :js, :template => 'sessions/home.js.erb'

or

respond_to do |format|
   format.html {render :template => 'sessions/home.js.erb', :content_type => 'text/javascript'}
end

or

respond_to do |format|
   format.html {render :template => 'sessions/home.js.erb', :content_type => 'application/javascript'}
end

Can somebody help me figure out what I need to do in order to get the browser to execute the javascript?


回答1:


Rails can deliver you code, but it's up to you to ensure that the code is loaded and executed on the clientside, otherwise it really is just text.

Jquery has a few handy helpers just for this thing

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

This will Load and Execute a Javascript file. Or you can use

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});

Both examples copied from the Jquery api docs. http://api.jquery.com/jquery.ajax/ and http://api.jquery.com/jquery.getscript/




回答2:


Overwrite the response content type. Read more about the response object here: http://guides.rubyonrails.org/action_controller_overview.html#the-response-object

Try out this:

def action
  response.content_type = Mime[:js]
  render js: "alert('got here');"
end

Or for all actions:

before_filter :force_js

def force_js
  response.content_type = Mime[:js]
end

Or with respond_to:

def action
  respond_to do |format|
    format.any(:html, :js) { render js: "alert('got here');" }
  end
end


来源:https://stackoverflow.com/questions/26920304/rails-4-force-browser-to-execute-javascript-response-instead-of-displaying-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!