[英]Rails3 renders a js.erb template with a text/html content-type instead of text/javascript
我正在用3.0.0.beta3构建一个新的应用程序。 我只是尝试将js.erb模板呈现给Ajax请求以执行以下操作(在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
目前,我的get_pubmed_data.js.erb模板很简单
alert('<%= @publication.title %>')
服务器正在响应以下内容
alert('Evidence for a herpes simplex virus-specific factor controlling the transcription of deoxypyrimidine kinase.')
这是完全没问题的,除了浏览器中没有任何事情发生,可能是因为响应的内容类型是'text / html'而不是'text / javascript',如此处部分重现的响应标题所示:
Status 200
Keep-Alive timeout=5, max=100
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/html; charset=utf-8
这是一个错误还是我错过了什么? 谢谢你的帮助!
我终于能够通过强制它在响应中获得正确的内容类型:
respond_to do |format|
format.js {render :content_type => 'text/javascript'}
end
使用Rails 3.1.1我遇到了类似的问题。 即使我在控制器中明确提到了format.js,我的回复也会呈现为html。 原来问题是我的资产中有jquery.js文件并被模板加载。 jquery-rails使用自己的jquery副本并加载这些文件导致rails因某些原因将响应呈现为html。 可能会帮助其他人坚持这个问题。
我遇到了同样的问题,事实证明我在我的控制器上创建了一个名为content_type的方法,该方法覆盖了默认值。
有一个类似的问题,其中js文件将作为文本文件加载,但最后它只是我的scrits加载错误的顺序。
更换
<%= javascript_include_tag :all %>
同
<%= javascript_include_tag "jquery.min" %>
<%= javascript_include_tag "jquery-ui.min" %>
<%= javascript_include_tag "rails" %>
还要注意,getscript方法
即替换:
onClick="<%= get_pubmed_data_path(:format => :js) %>"
有:
onClick="$.getScript('<%= escape_javascript(get_pubmed_data_path(:format => :js)) %>');"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.