0

Using last versions of jQuery 1 or 2, I have this simple code that makes a request and shows the result :

var url1 = "cache/1";

var callback1 = function(data, statusText, response){
    $("#result1").html("status :"+response.status);
    $("#result1").append("<p>"+JSON.stringify(data)+"</p>");
};

$(function() {

    $("#query1").on ("click", function(){
        $.ajax({
            url: url1,
            cache: true,
            dataType: 'json',
            ifModified: true,
            success:callback1
        });
    });
});

On the first request, I read my Json data. On the second request, I have a 304 response as expected, and data is undefined.

How can I show data from the browser cache ?

4
  • 1
    You should get the same value in data as you did the first time around. Check in the Net tab of your developer tools to make sure the request you are making actually is an if-modified-since one. Commented Apr 6, 2015 at 8:48
  • Actually it's an If-None-Match and it works when I make a direct chrome GET with the url Commented Apr 6, 2015 at 8:55
  • This should be completely transparent. You get the exact same data object in a success callback that runs after a 304. Commented Apr 6, 2015 at 11:05
  • I did it again with if-modified-since and now it works perfectly. But I've changed a lot of things in the server, and I think I have put some bad ETag format. As I forced the 304 by the server, maybe the client was not able to find the correct document associated to the bad ETag. I'll work on that later. Commented Apr 6, 2015 at 19:01

1 Answer 1

1

The documentation of ifModified

ifModified (default: false)
Type: Boolean
Allow the request to be successful only if the response has changed since the last request.

Says it all, I guess. Don't use it, it does not do what you think.

$(function() {
    $("#query1").on("click", function(){
        $.get("cache/1").done(function (data, statusText, response) {
            $("#result1")
                .html("status :"+response.status);
                .append("<p>"+JSON.stringify(data)+"</p>");
        });
    });
});

Don't try to steer caching from the client. That's the server's task. Set proper caching headers and the client will work on its own.

Sign up to request clarification or add additional context in comments.

1 Comment

Using if-modified-since, you can use cache=true or remove it as you wish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.