Created
April 12, 2013 09:14
-
-
Save benvium/5370738 to your computer and use it in GitHub Desktop.
AppFurnace: Utility function to load data from a .json file in the Files tab
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
| /** | |
| * Utility function to load JSON file a .json file in the Files tab. | |
| * | |
| * Params: | |
| * @filename - the filename to use. Use the path to the file, e.g. "data.json" for a file in the root, or "data/content.json" for a file in a folder called content. | |
| * @callback - a function to call with the data when it's loaded. You'll need to provide a function with a parameter called 'data'/. e.g. function (data) { popup("I've got data!"); } | |
| * | |
| * Example: | |
| * | |
| * // Load a file called data.json.... | |
| * loadJSONFromFiles("data.json", function(data) { | |
| * _.each(data, function(d) { // for each item.. | |
| * log( d.name " likes the color " + d.color); // .. log out the name and favorite color of each person. | |
| * }); | |
| * }); | |
| * | |
| * // data.json looks like this: | |
| * [ | |
| * { | |
| * "name":"Ben", | |
| * "color":"Blue" | |
| * }, | |
| * { | |
| * "name":"Tom", | |
| * "color":"Orange" | |
| * } | |
| * ] | |
| */ | |
| function loadJSONFromFiles(filename, callback) { | |
| $.ajax({ | |
| url:"content/" + filename, | |
| success: function(data) { | |
| if (data) { | |
| if (_.isString(data)) { | |
| try { | |
| data = JSON.parse(data); | |
| } catch (ex) { | |
| popup(filename + " is not valid json"); | |
| callback( {} ); | |
| return; | |
| } | |
| } | |
| callback( data ); | |
| } | |
| }, | |
| error: function(xhr) { | |
| popup("Failed to load " + filename + " server returned " + xhr.status); | |
| callback({}); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment