0

My application caches data locally. When data is requested, the cached copy is returned immediately and an ajax call is made in the background to check for any updates from the server. If there are any updates, they're pushed to the calling code.

What I'd like to do is check for a 304 response to the ajax call and not push to the caller if they've already been given the most up-to-date data. However, it seems that the xhr status is always 200, even if the server returns a 304 (which I can verify by looking at the raw response in the network tab of the chrome developer tools).

I've done some googling and it seems this is the expected behavior. But I've also found some mention that it's possible to override this behavior by setting an if-modified-since header. Unfortunately, I haven't seen a concrete example of how to accomplish this (and my naive attempt to set the header to new Date() didn't seem to work).

It looks like this is possible in jQuery by setting ifModified = true, but I'm trying to do this w/o jQuery.

I suppose I could just include some sort of version stamp in the actual data and manually compare it with my cached data, but it seems like it would be a lot nicer/cleaner to use the 304 response if at all possible. Can anyone point me in the right direction?

herbrandson
  • 2,357
  • 2
  • 30
  • 44
  • 1
    Even though the question I referred to says "jQuery" in the title, the accepted answer shows how to do this without jQuery. In your case, since you have the locally-stored data, you have the information necessary for `setRequestHeader` and so you can set it (and therefore get the 304 passed back to you). – T.J. Crowder Jun 21 '14 at 07:16
  • Thanks @T.J.Crowder! I guess my google-foo is off tonight. I couldn't seem to find that :( – herbrandson Jun 21 '14 at 07:28
  • No worries. Taught me something, too. :-) I thought 304s were always hidden by XHR. And your title is going to be a good hit in future searches, whereas that other question's title is a bit (no pun) hit and miss. FWIW, there's also a [`getResponseHeader` method](https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest#getResponseHeader()) you could use to get the `Last-Modified` header, if you wanted to use that... I have no idea how well-supported it is, but MSDN, MDN, and [the spec](http://www.w3.org/TR/XMLHttpRequest/) all list it... – T.J. Crowder Jun 21 '14 at 08:01

0 Answers0