我使用tonic.php(http://peej.github.com/tonic/)库创建我的REST资源。数据非常稳定,并且缓存时间长可能更可取。我设置了缓存头(使用tonic.php库):如何缓存REST资源的不同格式/表示形式?
$lastModified = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT';
$expires = gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + $httpCacheDuration)) . ' GMT';
$response->addHeader('Cache-Control', 'public,max-age='.$httpCacheDuration.',must-revalidate');
$response->addHeader('Expires', $expires);
$response->addHeader('Last-Modified', $lastModified);
的问题是,当请求HTML卷曲呼叫到一个PHP网页制作和返回的HTML被放入响应正文:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?identifier=' . $identifier);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
curl_close($ch);
$response->body = $html;
这个返回的页面然后通过对同一个资源的AJAX调用获取实际数据,但是接受标头为“application/json”而不是“text/html”。 的AJAX调用使用jQuery做,如果我设置
cache: true
jQuery的$
与阿贾克斯接受我的资源的调用:text/html的将只显示数据作为JSON,而不是网页(火狐)或抛出一个错误(IE8)。 代码:
switch ($format) {
case 'html':
$response->addHeader('Content-type', 'text/html');
$lastModified = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT';
$expires = gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + $httpCacheDuration)) . ' GMT';
$response->addHeader('Cache-Control', 'public,max-age='.$httpCacheDuration.',must-revalidate');
$response->addHeader('Expires', $expires);
$response->addHeader('Last-Modified', $lastModified);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIE, $strCookie);
curl_setopt($ch, CURLOPT_URL, url . '?identifier=' . $identifier);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
curl_close($ch);
$response->body = $html;
return $response;
break;
case 'json':
$result = DataManager::get($identifier);
if (empty($result)) {
$response->code = Response::NOTFOUND;
return $response;
}
$lastModified = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT';
$expires = gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + $httpCacheDuration)) . ' GMT';
$response->addHeader('Cache-Control', 'public,max-age='.$httpCacheDuration.',must-revalidate');
$response->addHeader('Expires', $expires);
$response->addHeader('Last-Modified', $lastModified);
$response->addHeader('Content-type', 'application/json');
$response->code = Response::OK;
$response->body = json_encode($result);
return $response;
break;
// we don't have a suitable format, so do a 406 response instead
default:
$response->code = Response::NOTACCEPTABLE;
$response->addHeader('Content-type', 'text/plain');
$response->body = getErrorPage(Response::NOTACCEPTABLE);
return $response;
break;
}
添加
$response->addHeader('Vary', 'Accept');
使得它的工作。然而,json永远不会被缓存,这会导致与设置缓存相同的行为:在Jquery ajax调用中为false。
如何缓存2个不同的表示并让浏览器为请求的accept-header显示正确的表示?
如果您更改网址,那么该怎么办?如果我了解您的问题,则浏览器缓存不会根据请求中的Accept标头区分内容。如果将'.json'附加到JSON数据包的URL,则浏览器将能够根据URL进行缓存。 – Cheeso 2012-07-17 05:40:03
谢谢。这样做的工作也让你想知道什么点不同:接受是如果它不工作,并且必须使用“hacky解决方法”。 – 2012-07-27 06:32:56
猜测......也许'Vary'是堆栈中不太成熟的部分之一。 – Cheeso 2012-07-27 16:50:24