2014-02-05 62 views
1

Rails的重定向呈現HTML,但我有一個奇怪的問題,重定向和我的Rails應用程序3.2渲染的瀏覽器不顯示它

從我創建控制器動作,我已經有了respond_to代碼塊

// request type here is JSON 
respond_to do |format| 
    format.json { redirect_to(v2_promote_path(@challenge), content_type: "text/html") } 
end 

...它重定向到在同一個控制器中執行以下操作如下:

def promote 
    // request type is JSON here 
    request.format = :html 
    @challenge = Challenge.find(params[:id]) 

    respond_to do |format| 
    format.html { render '/challenges/v2/promote_challenge.html.erb'} 
    end 
end 

奇數部分是這會呈現HTTP響應中的promote_challenge模板,但瀏覽器不顯示它。

重定向操作獲取應用程序/ JSON的請求類型,即使我明確地將其設置爲HTML在重定向呼叫時,HTML仍然只得到的反應,而不是瀏覽器中呈現。

問:爲什麼我得到HTML的響應,而不是瀏覽器?

下面是請求/響應頭:

REQUEST: 
GET /v2/challenges/18236/promote HTTP/1.1 
Host: localhost:3000 
Connection: keep-alive 
X-XSRF-TOKEN: asldfkasldkfas= 
X-Requested-With: XMLHttpRequest 
Accept: application/json, text/plain, */* 
Referer: http://localhost:3000/v2/challenges/preview 

RESPONSE: 
HTTP/1.1 200 OK 
Content-Type: text/html; charset=utf-8 
Cache-Control: max-age=0, private, must-revalidate 
Connection: close 

回答

1

你可以嘗試使用format呢?

redirect_to(v2_promote_path(@challenge), format: :html) 
+0

嘗試過,但得到了完全相同的行爲。謝謝 – yalestar

+0

我認爲這裏有一個限制/假設與Rails阻止你使用正常的約定來做這件事。這篇文章應該勾勒出一個哈克的方式(見接受的答案)做到這一點:http://stackoverflow.com/questions/18629811/rails-redirect-to-format-h​​tml-sends-response-in-js。但是,我認爲你可能想呈現一個JS模板你的HTML來代替,而在客戶端的內容替換(見最後答案) – steakchaser

+0

你是absotively權,Steakchaser先生! – yalestar

1

接受的hacky解決方案很醜陋;我們可以同意這一點。它只是讓rails告訴客戶端執行重定向的Javascript。

一個更清潔的解決方案,在我看來,是處理你的成功回調重定向在JS:

render :json => { status: 'success' }在軌 然後像做

success: function(data) { 
    // Send user to next page. 
    window.location.href = "http://www.myawesomesite.com/page"; 
}, 
在JS

+0

我知道它不乾淨。但它絕對有效。 – Penguin