Created
September 30, 2016 18:54
-
-
Save meetar/4d90c81e91f691ebdca1c940c1ed7bc0 to your computer and use it in GitHub Desktop.
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
// load a file from a URL | |
function readTextFile(file, callback, errorback) { | |
var rawFile = new XMLHttpRequest(); | |
// only change this if you know you want to force a particular mime type and are having trouble | |
// rawFile.overrideMimeType("application/json"); | |
try { | |
rawFile.open("GET", file, true); | |
} catch (e) { | |
console.error("Error opening file:", e); | |
} | |
rawFile.onreadystatechange = function() { | |
// readyState 4 = done | |
if (rawFile.readyState === 4 && rawFile.status == "200") { | |
callback(rawFile.responseText); | |
} else if (rawFile.readyState === 4 && rawFile.status == "404") { | |
throw new Error("404 – can't load file", file); | |
} else if (rawFile.readyState === 4 && rawFile.status == "401") { | |
throw new Error("401 – can't load file", file); | |
} else if (rawFile.readyState === 4) { | |
throw new Error("Problem with "+ file); | |
} | |
}; | |
rawFile.send(null); | |
} | |
readTextFile(url, function(text){ | |
// do the stuff! | |
try { | |
data = JSON.parse(text); | |
} catch(e) { | |
console.warn('Error parsing json:', e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment