简体   繁体   中英

Rails3 renders a js.erb template with a text/html content-type instead of text/javascript

I'm building a new app with 3.0.0.beta3. I simply try to render a js.erb template to an Ajax request for the following action (in publications_controller.rb):

def get_pubmed_data
    entry = Bio::PubMed.query(params[:pmid])# searches PubMed and get entry
    @publication = Bio::MEDLINE.new(entry) # creates Bio::MEDLINE object from entry text
    flash[:warning] = "No publication found."if @publication.title.blank? and @publication.authors.blank? and @publication.journal.blank?      
    respond_to do |format|
        format.js
    end
end

Currently, my get_pubmed_data.js.erb template is simply

alert('<%= @publication.title %>')

The server is responding with the following

alert('Evidence for a herpes simplex virus-specific factor controlling the transcription of deoxypyrimidine kinase.')

which is perfectly fine except that nothing happen in the browser, probably because the content-type of the response is 'text/html' instead of 'text/javascript' as shown by the response header partially reproduced here:

Status 200
Keep-Alive timeout=5, max=100
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/html; charset=utf-8

Is this a bug or am I missing something? Thanks for your help!

I finally was able to get the right content-type in the response by forcing it with:

respond_to do |format|
    format.js {render :content_type => 'text/javascript'}
end

With Rails 3.1.1 I ran into a similar issue. My response would render as html even though I had explicitly mentioned format.js in my controller. It turns out the problem was that I had jquery.js files in my assets and being loaded by the template. jquery-rails uses its own copy of jquery and having these files also loaded caused rails to render the response as html for some reason. Might help someone else stuck with this issue.

我遇到了同样的问题,事实证明我在我的控制器上创建了一个名为content_type的方法,该方法覆盖了默认值。

had a similar problem where the js file would load as a text file, but in the end it was just my scrits which were loading in the wrong order.

replace

<%= javascript_include_tag :all %>

with

<%= javascript_include_tag "jquery.min" %>
<%= javascript_include_tag "jquery-ui.min" %>
<%= javascript_include_tag "rails" %>

Also to note, the getscript method

ie replace:

onClick="<%= get_pubmed_data_path(:format => :js) %>"

with:

onClick="$.getScript('<%= escape_javascript(get_pubmed_data_path(:format => :js)) %>');"

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