[英]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.