Print

Print


If all you want to do is load external json as a string, you can do it
using syntax almost identical to what you suggest. Just change your
data.json file so the content is

var data = ' [include your json here, be sure to escape things properly]';

Then just load this file before your external script e.g.:

<!cript language="javascript" src="data.json"></script>
<!cript language="javascript" src="external_script.js"></script>

Within external_script.js, you can reference the data variable just as you
would have had it been defined in external_script.js.

Depending on what you're doing with your json, it may or may not be a good
approach, but it will work.

kyle

On Wed, Apr 6, 2016 at 6:02 PM, Ken Irwin <[log in to unmask]> wrote:

> Hi folks,
>
> I'm working on a javascript project that currently has a bunch of JSON
> data defined inside the script; I'd like to move the data to a file outside
> the JS file so it can be updated without touching the script, but I'm
> running up against a few challenges externalizing the data.
>
> The static JSON file lives in the same directory with the script.
>
> If I had my druthers, I'd to it PHP style, but I don't think JS works this
> way:
> =====
> External file:
> [all this JSON]
>
> Script:
> var data = include ('data.json');
> ====
> All the options I find for loading external files are all AJAX-y, whereas
> what I really want is something synchronous - the script doesn't go on
> until the data loads.
> I've also had some lexical scope issues where I can get the data inside
> the getJSON() function, but then have trouble transporting the data out of
> that function into the rest of the script.
>
> Does anyone know of a good way to accomplish this? I imagine there's some
> incantation that I can perform, but I'm struggling to find it.
>
> Thanks,
> Ken
>