Rails3 使用 text/html 内容类型而不是 text/javascript 呈现 js.erb 模板

2023-12-22

我正在使用 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails3 使用 text/html 内容类型而不是 text/javascript 呈现 js.erb 模板 的相关文章

随机推荐