0

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?

1

2 Answers 2

1

Like this!

$.getJSON('path', function (arrayOfNames) {
// do things with your arrayOfNames
} );
Sign up to request clarification or add additional context in comments.

3 Comments

You're missing a closing ) but yeah this will work: jsbin.com/javiyesupi/1/edit?html,console,output
Can I somehow do this synchronously?
With two different files?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.