Cache busting AJAX requests and redirects

AJAX get and head requests are cached by default. This can cause problems when AJAX requests use the same URLs as a user would use during normal site navigation. jQuery can disable caching on a global or per-request basis. When doing so, jQuery adds a _={timestamp} parameter to the query string which should make each request unique. However, there are cases where an AJAX request results in a redirect which jQuery will happily follow. When that happens the _={timestamp} isn’t automatically appended to the new request, so the final response can still end up being cached by the browser even when you’ve told jQuery not to cache it. You can get around this in 2 ways:

  1. Make sure all redirects persist the _={timestamp} parameter, if present
  2. Add the proper header response parameters to prevent the browser from caching the request.

Here’s an easy way to implement the 2nd solution in Rails:

[gist id=a879915f7921a3ca11c3 file=application_controller.rb]

There is something to be learned from a rainstorm.
When meeting with a sudden shower, you try
not to get wet and run quickly along the road.
By doing such things as passing under the eaves
of houses, you still get wet. When you are
resolved from the beginning, you will not be
perplexed, though you will still get the same
soaking. This understanding extends to all things.

— Yamamoto Tsunetomo, Hagakure: The Book of the Samauri