I get some json data with ajax when the page DOM is loaded using jQuery like this:
$(document).ready(function(){
getData();
});
...where getData() is a simple jQuery ajax call, something like this:
function getData(){
$.ajax({cache: true, dataType: 'json', url: '/foo/bar'});
}
The Expires header for this request is set to some time in the future, so the next time I load the page, the ajax call should use the cached data. Firefox 3 does not.
But, if I instead ask for the data like this:
$(document).ready(function(){
setTimeout("getData()", 1);
});
Firefox does respect the Expires header, and uses the cache. Any ideas why this would be?
This page mentions that browsers may treat ajax calls that occur when a page loads differently from ajax calls that occur in response to a user UI event.
Edit: I forgot to include the http headers in my original post. I think the headers are fine, because the caching works as long as the request isn't made in an ajax call when the page loads. If I visit the url that the ajax call uses in my browser URL bar, caching works, and as I explain above, caching works if I add a little delay to the ajax call.
Request headers
- Host 10.0.45.64:5004
- User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.9) Gecko开发者_运维技巧/20100824 Firefox/3.6.9
- Accept application/json, text/javascript, /
- Accept-Language en-us,en;q=0.5
- Accept-Encoding gzip,deflate
- Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
- Keep-Alive 115
- Connection keep-alive
- X-Requested-With XMLHttpRequest
- Cookie
Response headers
I set the Expires header to 1 week in the future so that users only need to refresh once a week.
- Date Wed, 04 May 2011 15:32:04 GMT
- Last-Modified Wed, 04 May 2011 15:32:03 GMT
- Expires Wed, 11 May 2011 15:32:03 GMT
- Content-Type text/javascript
- Cache-Control Public
- Connection close
Define an error handler in the $.ajax() call and inspect the response headers (using jqXHR.getAllResponseHeaders() where jqXHR is the jQuery Ajax object, status code, and responseText.length. You may find that the request is successful, but jQuery treats them as unsuccessful. I've recently had a similar issue with cached files and $.ajax(), and it turns out that sometimes when files are loaded when the browser is offline, or from a local file, return a status code of 0. Because the status doesn't fall in the range of success codes (200-300), jQuery considers the request to have failed. See this for what I did to fix this issue. Basically, in your error handler, you can check the responseText.length. If it is non-empty, consider the request successful and parse the JSON using JSON.parse(). BUT!!! you have to make sure on your server-side that invalid requests are empty.
精彩评论