Reputation: 26281
I have two JSON sources: getCachedJSON.php and getNotCachedJSON.php. As suggested by the names, the client should cache the results from the first but not the second. Both of these files will issue the appropriate headers to tell the client to cache or not cache the data.
How is this best accomplished?
I came up with the following, but don't know if this is how it should be done. And if it is the right way, should the cached JSON be first requested and then the non-cached JSON, or the other way around?
$.ajax({
//cache: true,
url: "getCachedJSON.php",
dataType: "json",
success: function(cachedJSON) {
$.ajax({
//cache: false,
url: "getNotCachedJSON.php",
dataType: "json",
success: function(notCachedJSON) {
var allJSON = $.extend({}, cachedJSON, notCachedJSON);
console.log(allJSON);
}
});
}
});
Upvotes: 0
Views: 208
Reputation: 287
If you want to make a server request and cache it on the client side, you can make use of the browser's local storage.
You could do something along the lines of this:
var allData = cached(nonCached);
function cached(callback){
var cachedData = localStorage.getItem('cached');
// if locally stored data is found, pass it to the callback
if(cachedData){
callback(JSON.parse(cachedData));
} else {
// Else get it from php script, store it, and pass to callback
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(cachedData) {
var key = 'cached';
localStorage.setItem(key, JSON.stringify(cachedData));
callback(cachedData);
}
});
}
}
function nonCached(cachedData){
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(nonCachedData) {
return $.extend({}, cachedData, nonCachedData);
}
});
}
Upvotes: 0
Reputation: 1881
Browser manages caching for you. Each time when you're making GET request the browser check if it has this resources in its cache. If it has it then request is not made. To tell browser how to control caching you have to use http headers like cache-control and max-age (try to google for details). You have to set these headers when browsers access you server. You can use chrome's dev tools (network) to inspect if there is any requests made. There you will see if resource is obtained from cache or from request.
If you want event better cache control I recommend you to use service workers or browser sql databases.
Hope I understood your question right.
Upvotes: 1