Last active
September 19, 2015 21:56
-
-
Save romidane/d98e587550d13eaf7e11 to your computer and use it in GitHub Desktop.
Simple cached HTTP requests with Jquery Supports both GET and POST with data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function fetchData(url, options, cb){ | |
| if(!cb) throw new Error('Please suply a callback function!'); | |
| if(!fetchData._cache) fetchData._cache = {}; | |
| var settings = { | |
| method: "GET", | |
| url: url | |
| } | |
| extend(settings, options); | |
| if(!fetchData._cache[url]){ | |
| $.ajax(settings) | |
| .done(function(data){ | |
| fetchData._cache[url] = data; | |
| cb(null,data); | |
| }) | |
| .fail(function(jqXHR, textStatus, errorThrown){ | |
| var errData = { | |
| jqXHR: jqXHR, | |
| textStatus:textStatus, | |
| errorThrown:errorThrown | |
| }; | |
| cb(errData, null); | |
| }) | |
| } else{ | |
| cb(null,fetchData._cache[url]); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function extend(source, target) { | |
| if (!target) return; | |
| // All or nothing approach | |
| for( var key in target ) { | |
| if(target.hasOwnProperty(key)){ | |
| source[key] = target[key]; | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Example using Defaults | |
| fetchData("http://someurl.com", null, function(err, data){ | |
| if(err) { | |
| // do something about it | |
| } | |
| //No errors? Sweet let do some work! | |
| //... | |
| }) | |
| //Example using options overide | |
| fetchData("http://someurl.com", { method: 'post'}, function(err, data){ | |
| if(err) { | |
| // do something about it | |
| } | |
| //No errors? Sweet let do some work! | |
| //... | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment