2

在我的网站中,每个页面都可以返回 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
    }
});

这个问题在火狐中。在 chrome 中一切正常

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

4

2 回答 2

1

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

/foo.html 与 /foo.json

或者

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

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

于 2013-04-13T08:59:49.347 回答
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>";
}
于 2013-04-13T08:42:47.793 回答