views:

517

answers:

2

This is the XMLHttpRequest:

$.ajax({
    method: "get",
    url: "getPage.php",
    data: $data,
    dataType: 'json',
    timeout: 2000,
    success: function(result) {
        handleContent(result);
        }
    });

This is getPage.php?data=data

header("Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT");
header("Cache-Control: max-age=" . $offset . ", public");
header("HTTP/1.1 301 Moved Permanently");
header("Location: $location);

This is $location:

header("Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT");
header("Cache-Control: max-age=" . $offset . ", public");
print $print;

The client browser properly caches $location. However it does not cache the redirect in getPage.php?data=data

Every time the ajax-request is called it requests a GET getPage.php?data=data.

I would like it to automatically GET $location instead (or rather try GET $location and get the page from cache).

Is this not what 301 Permanent Redirect is for? Creating a redirect which is cached by the browser (plus some proxy, search engine etc. stuff of course)?

Please do not question why I choose to do it this way. I have reasons for this which I am not going to go into here. All I want is an answer and possibly a solution which lets the 301 redirect get cached resulting in no GET requests at all after a first request.

Thanks in advance!

+1  A: 

This thread and it's comments contain ways to handle this exact problem, although the presented solutions for the problem still steem a little 'flakey' (mostly because of browser implementations at the moment):

http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call

I hope you find it informative.

ChristopheD
+4  A: 

Most browsers don't cache redirects. Steve Souders tested this as part of his UA Profiler browser performance test. Here's the description from the FAQ:

Many pages use redirects to send users from one page to another, for example http://google.com/ redirects to http://www.google.com/. Unfortunately, most browsers don't pay attention to the cache headers of these redirects, and force the user to endure the redirect over and over again.

Also see the results of the test so far.

In other words, you won't be able to get redirects cached, except by waiting for browsers to make that the default option. Firefox 3.5 and Chrome cache them (though not everybody is quite as happy about that).

mercator