2013-04-13 49 views
2

在我的網站中,每個頁面都可以返回html和json。 如果請求是正常的頁面返回html,如果請求是AJAX頁面返回json。當我使用AJAX時,Firefox忽略緩存控制無存儲,無緩存

問題是,當我需要json響應時,firefox會緩存html響應。 在這兩種情況下的響應頭不帶緩存選項

Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
Connection Keep-Alive 
Date Sat, 13 Apr 2013 08:31:06 GMT 
Expires Thu, 19 Nov 1981 08:52:00 GMT 
Keep-Alive timeout=5, max=100 
Pragma no-cache 

這就是我正在做的AJAX請求:

$.ajax({ 
    url: window.location.href, 
    dataType: 'json', 
    //cache: false, 
    success: function(data) { 
     // here I get html, (must be json) 
     // If I set "cache: false" then all is ok 
    } 
}); 

這個問題在Firefox瀏覽器。在鉻一切正常

我認爲這是因爲我發送請求在我現在定位的頁面上。因爲如果我在window.location.href上更改url。 '?a = 1',如果我已經在頁面window.location.href。 '?a = 1'AJAX以我想要的方式返回json。

+0

這是很奇怪的行爲; no-cache在Firefox中一般工作!你有鏈接到顯示此行爲的頁面嗎? –

+0

我還沒有鏈接,它在本地機器上。它是好的,沒有緩存的作品。但是,如果頁面已經在Firefox中打開(就像我的情況一樣),並且您在此頁面上執行AJAX請求,則響應會從緩存中獲取。我同意@allyourcode,它更好地使用不同的URL來獲取JSON和HTML。現在,我有/ foo頁面和/foo.json json – Ildar

+0

重點是你描述的是no-cache _not_工作。這很奇怪,因爲我剛剛在本地嘗試了您的示例,並且它工作正常。因此,希望看到一個測試用例,它不工作,所以我可以調試它並修復任何問題... –

回答

1

你爲什麼不改變你URL方案,以便使用不同的URL訪問JSON和HTML?例如。

/foo.html與/foo.json

/富?格式= HTML與/富?格式= JSON

不要把它作爲一種解決方法適用於Firefox;您希望儘可能避免降低緩存能力,因爲高度緩存的網站對您的用戶執行速度更快,並且可以減少爲網站提供服務所需的資源數量。

+0

好主意,謝謝,也許我會這麼做 – Ildar

1

您可以設置高速緩存控制,以沒有緩存上的任何文件是在負責處理Ajax請求

header('Cache-Control: no-cache, must-revalidate'); 

,或者試試這個:

if($_SERVER['HTTP_ORIGIN'] == "http://example.com") 
{ 

    header('Access-Control-Allow-Origin: http://example.com'); 
    header('Cache-Control: no-cache, must-revalidate'); 
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 
    header('Content-type: application/json'); 
    //your code here 

}else{  
    header('Content-Type: text/html'); 
    echo "<html>"; 
    echo "<head>"; 
    echo " <title>Another Resource</title>"; 
    echo "</head>"; 
    echo "<body>", 
    "</body>", 
    "</html>"; 
} 
+0

它已經是Cache-Control:no-cache,必須重新驗證。但它並沒有幫助 – Ildar

+0

所以即時猜測你也設置內容類型返回json: 標題('Content-type:application/json'); – jycr753