0

This ain't working:

   $(document).ready(function () {
    var getJ = null;
    var url = 'JSON file URL here';
    $.getJSON(url, function (data) {
         getJ = [...data]
    });
   }); 
   document.write(getJ[0].Tag)

(The tag here contains some data from JSON file)

This only works when I output getJ inside the function; however, I want it outside.

1

1 Answer 1

1

A few things are in play here:

  1. Your $(document).ready function is a callback which is executed whenever the document is fully loaded. Your document.write call does not have a callback so it is most certainly going to be executed before anything you're doing in .ready, and getJ has not yet been assigned.

  2. Your $.getJSON call is also accepting a callback function which means it waits for the request to be executed before it can set the result. Those functions are all delayed whereas document.write is not. You can either make the GET request synchronous (set async to false). You can do that by using the full $.ajax call: https://stackoverflow.com/a/2765848 OR you can just start chaining your functions together as synchronous calls are deprecated and may not be supported for very long. Here is an example of how you would do this with jQuery: https://stackoverflow.com/a/16045729

  3. Although var in JS will make the variable accessible in a global scope, please don't confuse yourself or others later by declaring it in a scope that you don't even plan to use it in. You want to access this variable outside of your $(document).ready call so you should declare it before that function to make it clear that you expect it to be changed.

Sign up to request clarification or add additional context in comments.

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.