Reputation: 18068
I contents of this site to the file at App/data/names.js
directory in my solution: https://raw.githubusercontent.com/dominictarr/random-name/master/names.json
I did it because the array is too big to put in my file where I write my code and initialize a variable with it explicitly. But still, I would like to assign it to the variable I created. I have mind something like this.
var arrayOfNames = readJSonFromFile("path");
Is it possible to achieve?
Upvotes: 0
Views: 63
Reputation: 4125
Like this!
$.getJSON('path', function (arrayOfNames) {
// do things with your arrayOfNames
} );
Upvotes: 1
Reputation: 386
You can fetch the document with an HTTP request from JavaScript, sort of like this:
function do_something(arrayOfNames) {
console.log(arrayOfNames)
}
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://raw.githubusercontent.com/dominictarr/random-name/master/names.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
do_something(JSON.parse(xhr.responseText))
}
}
}
xhr.send()
Note that this may not work on ancient browsers. Depending on whether you're using some JavaScript framework there is probably a shorter solution.
Upvotes: 0