开发者

Safari caches JSONP requests locally

I have a page that makes the same JSONP request multiple times in a single page load. In most browsers this works fine, but Safari caches the response locally until such time as the page is reloaded. Even when I send back a Cache-Control: no-cache header on the response.

consider the following example code:

var plcbCnt = 0;
var plcb = "plcb" + plcbCnt;
while(window[plcb]){
    plcb = "plcb" + (++plcbCnt);
}

$.ajax({
    "url": "http://myserver.com/echoDate",
    "dataType": 'jsonp',
    "jsonp": "cb",
    "jsonpCallback": plcb,
    "success": function(resp){
        $("#pants").html($("#pants").html() + resp + "<br/>");
    }
});

First request returns:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 28
Content-Type: application/javascript
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
Set-Cookie: ASP.NET_SessionId=g0zwq2qiaheh4145cudddmjo; path=/
X-Powered-By: ASP.NET
Date: Wed, 20 Oct 2010 18:22:12 GMT

plcb0('634231777326425375');

Subseq开发者_高级运维uent calls serve from the local cache, rather than hitting the server like they should.

You're probably wondering what that extra part at the beginning is about setting the callback function. I could just use a random number there, right? Not really. We avoid extra rendering work by caching the entire output, based on the requested URL. So if I change the callback function name on each request, I lose the benefits of the server cache.

Best I can think of is to add a garbage parameter on the request, and make the server cache strip that out of the URL when making the cache key. But I wanted to see if there was a better option first... something about Safari that I don't know about.


Try adding a hash parameter - the browser will see this as a new request, and won't use its cache, but everything beyond the hash gets stripped out before the request is made. Give this a whirl and see it it works:

var callback = '#call' + new Date().getTime();
$.ajax({
    "url": "http://myserver.com/echoDate" + callback,
    "dataType": 'jsonp',
    "jsonp": "cb",
    "jsonpCallback": plcb,
    "success": function(resp){
        $("#pants").html($("#pants").html() + resp + "<br/>");
    }
});


it seems it happens on IE also, you can set cache to false in the ajax call:

$.ajax({  
    /*cache: false,*/
    "url": "http://myserver.com/echoDate",
    "dataType": 'jsonp',
    "jsonp": "cb",
    "jsonpCallback": plcb,
    "success": function(resp){
        $("#pants").html($("#pants").html() + resp + "<br/>");
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜