Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

http - Can't the browser just use its cache from prior ajax calls?

I am trying to rely upon the browser cache to hold JSON data returned from AJAX calls in jQuery.

Normal browser activity relies upon the browser cache all the time. Example: jpg and gif images are not refetched on a page reload.

But when I try using jQuery getJSON ajax calls, I cannot seem to avoid fetching the data from the server.

My returned headers look like this (confirmed with firebug):

Transfer-Encoding: chunked
Date: Wed, 05 Aug 2009 02:55:39 GMT
Content-Type: text/plain; charset=ISO-8859-1
Expires: Wed, 05 Aug 2009 03:55:39 GMT
Cache-Control: max-age=3600

Yet an immediate refresh of the page causes identical requests to hit the server.

I've seen several postings about avoiding caching behavior, which isn't what I need. I've seen several postings about utilizing caching, but those all seem to rely upon saving data in the DOM. I want something that behaves just like cached images do during a page reload.

Cant the browser just fetch it from it's own cache?

--x--x--x--x UPDATE --x--x--x--

Much to my disappointment, several respectable folks agree that this isn't just possible. Some even argue that it shouldn't be (which still baffles me).

Stubburn to a fault, I tried the following:

I set the Etag header on all outgoing pages I want to be cached (I pick a few choice URL arguments that represent the data I'm requesting and just use that for the Etag value)

At the beginning of the next request, I simply check if the 'If-None-Match' header is in the request. If so, then the browser isn't caching the request like I wanted, so I sent a 304 Not Modified response.

Testing shows that Firefox won't cache my request (but I can still avoid the 'fetch the expensive data' part of my cgi), while IE6 will actually cache it (and wont even attempt fetching back from the server).

It's not a pretty answer, but it's working for me for now
(those pesty full-page refreshes of graph data wont be so slow or expensive now).

(What? I'm running IE6! OMG! Oh look a squirrel!)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ajax caching is possible and predictable (at least in IE and Firefox).

This blog post discusses Ajax caching and has a demo web page:

http://blog.httpwatch.com/2009/08/07/ajax-caching-two-important-facts/

There's also a follow up by Steve Souders on the F5 issue:

http://stevesouders.com/tests/ajax_caching.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...