【问题标题】:Firefox ignores Cache-Control no-store, no-cache when I use AJAXFirefox 在我使用 AJAX 时忽略 Cache-Control no-store, no-cache
【发布时间】:2013-04-13 08:38:59
【问题描述】:

在我的网站中,每个页面都可以返回 html 和 json。 请求正常页面返回html,请求AJAX页面返回json。

问题是当我需要 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 中。在 chrome 中一切正常

我认为是因为我正在我现在所在的页面上发送请求。因为如果我更改 url 例如在 window.location.href 上。 '?a=1' 如果我已经在页面 window.location.href 上。 '?a=1' AJAX 以我想要的方式返回 json。

【问题讨论】:

  • 这是很奇怪的行为; no-cache 通常在 Firefox 中有效!您是否有指向显示此行为的页面的链接?
  • 我没有链接,它在本地机器上。没关系,无缓存有效。但是,如果页面已经在 Firefox 中打开(就像我的情况一样)并且您正在此页面上执行 AJAX 请求,那么响应会从缓存中获取。我同意@allyourcode,最好使用不同的 URL 获取 JSON 和 HTML。现在,我有 /foo 页面和 /foo.json 用于 json
  • 重点是您所描述的是无缓存 工作。这很奇怪,因为我只是在这里本地尝试了您的示例并且效果很好。因此,我希望看到一个无法正常工作的测试用例,以便我可以调试它并解决任何问题......

标签: javascript firefox browser-cache


【解决方案1】:

您为什么不更改您的 URL 方案,以便使用不同的 URL 访问 JSON 和 HTML?例如

/foo.html 与 /foo.json

/foo?format=html 与 /foo?format=json

不要认为它是 Firefox 的解决方法;您希望尽可能避免降低可缓存性,因为高度可缓存的网站对您的用户来说执行速度更快,并减少了为您的网站提供服务所需的资源量。

【讨论】:

    【解决方案2】:

    您可以在负责处理 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>";
    }
    

    【讨论】:

    • 它已经是 Cache-Control: no-cache, must-revalidate。但这无济于事
    • 所以我猜你也将内容类型设置为返回 json: header('Content-type: application/json');
    猜你喜欢
    • 2022-11-17
    • 2022-12-09
    • 1970-01-01
    • 2012-11-03
    • 2011-11-26
    • 2019-07-09
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多