Grails: best way to send cache headers with every ajax call Grails: best way to send cache headers with every ajax call ajax ajax

Grails: best way to send cache headers with every ajax call


Here's what I finally figured out. Most javascript libraries --including jQuery, YUI, Mootools and Prototype -- send the X-Requested-With: XmlHttpRequest header on every ajax request.

For any request that sends this header, you can send a response header back that tells it to not cache.

Below is a Grails filter that prevents caching of ajax requests that identify themselves with the X-Requested-With: XmlHttpRequest header:

// put this class in grails-app/config/class AjaxFilters {    def filters = {        all(controller:'*', action:'*') {            before = {                if (request.getHeader('X-Requested-With')?.equals('XMLHttpRequest')) {                    response.setHeader('Expires', '-1')                }            }        }    }}

Some people prefer to use the Cache-Control: no-cache header instead of expires. Here's the difference:

  • Cache-Control: no-cache - absolutely NO caching
  • Expires: -1 - the browser "usually" contacts the Web server for updates to that page via a conditional If-Modified-Since request. However, the page remains in the disk cache and is used in appropriate situations without contacting the remote Web server, such as when the BACK and FORWARD buttons are used to access the navigation history or when the browser is in offline mode.

By adding this filter, you make Internet Explorer's caching consistent with what Firefox and Safari already do.

BTW, I've experienced the caching problem on IE8 and IE9. I assume the problem existed for IE7 and IE6 as well.


We use jQuery for all ajax calls so we add this block to our main.gsp (top-level layout):

<g:javascript>  jQuery(document).ready(function() {    $.ajaxSetup({      cache:false    });  });</g:javascript>

Also answered here