Mootools Ajax Caching
December 4th, 2007 in scripts | No Comments
Here’s a little add-on I wrote for Mootools 1.2b1. It’ll cache Ajax responses based on the url and parameters. Passing in an additional true argument will override any cache and make the request again. I haven’t tested it too extensively, but it should work for most things.
var CachedRequest = new Class({ Extends: Request, options: { onSuccess: function () { CachedRequest.cache.set(this.options.url + this.parameters, this.response); } }, send: function (options, refresh) { var parameters = options.data || options || this.options.data; switch($type(parameters)) { case 'element': parameters = $(parameters).toQueryString(); break; case 'object': case 'hash': parameters = Hash.toQueryString(parameters); } this.parameters = parameters.replace(/[^\w]+/g, ''); var cache = CachedRequest.cache.get(this.options.url + this.parameters); if (!cache || refresh) { return arguments.callee.parent(options, false); } else { this.response = cache; this.fireEvent('onComplete'); } } }); CachedRequest.cache = new Hash();
And here’s an example:
var req = new CachedRequest({'url':'page.php'}); req.send({ 'data': { 'param1': '23', 'param2': 'true' } }); //no request is made with this next call, the cache is used req.send('param1=23¶m2=true');

