How to Enable ajax request caching for semi dynami

2019-08-07 07:03发布

问题:

I have to cache json data for my phonegap applicaiton for 10 minutes how to do that? server response is already with the expiry headers.

Cache-Control:  max-age=315360000
Expires:    Sun, 12 Sep 2038 20:15:20 GMT

BUT jquery ajax request is not being cached.

回答1:

[a] Sometimes we need to enable and disable ajax request caching for browsers. can be done via below flag. cache: true

  • if set to true ajax request will start caching depending upon the content deposition header.

  • if set to false a unique timestamp will be appended to request so that request is never cached. http://www.exp.com/api/get_posts/?count=12&page=1&_=1381305201264

code:

 global_xhrAbort = $.ajax({
                    cache: true,
                    type: "GET",
                    timeout: 30000,
                    async: false,
                    url: finalurl,
                    data: null,
                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    dataType: "json",
                    complete: function () {
                    },
                    success: function (data) {
                        console.log('picked from server koimoi: success');
                        Page_topstoriesJson = GetJSONifNeeded(data); ;
                        HTMLSTORAGE_SET('landingpage', GetJSONstringfyifNeeded(data)); //will expire in ten mintues
                        doChangesForMainandTopStoriesSlider();
                        HideLoading();
                    }
                    ,
                    error: function (errmsg) {
                        alert_dialog('Request failed. Please check your internet connection or Press Refresh Button.',true);
                        console.log('index_devicreReadyError: ' + errmsg);
                    }
                });   

Jquery AJAX cache documentation : (default: true, false for dataType 'script' and 'jsonp') Type: Boolean If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

[b] Remember: Ctrl+R on chrome always loads new data from server, even if its cached. Open page in new window to see the results while testing.