Mattaus
Mattaus

Reputation: 41

Sharing Data Between Javascript Files

I have a script that generates a JSON formatted string. I want to use the data contained in this string in another script. I'm not sure where to even start. I've thought about running both scripts from the same directory and somehow outputting the JSON data into a text file and then loading it into the second script but this seems like more of a workaround than an actual solution. Is it possible to somehow call the second script from the first and pass it the data? Much like passing data between functions in a single script?

FWIW I have tried simply combining the functions the two scripts perform into one, but this has caused me countless headaches with no progress. For simplicity sake I'd prefer to keep the functions performed by each script separate (apart from the obvious data sharing requirement!).

Any advice or a point in the right direction would be greatly appreciated.

Upvotes: 0

Views: 1906

Answers (3)

user5525667
user5525667

Reputation:

If JSON data is less than 5 mb then you can use localStorage to save the output in browser.

In first js file:

function fOne(){
    var jsonStr = ''; //insert some json data here
    localStorage.setItem("myJson", JSON.stringify(jsonStr)); //save data
}

In your second js file:

function fTwo(){
    if (localStorage.getItem("myJson") !== null) {
        var passedJson = localStorage.getItem("myJson"); //get saved data anytime
    }
}

Upvotes: 3

Luple
Luple

Reputation: 491

So it actually depends what environment you are programming in. If its a web browser, all of the code is in the global space actually and is run in order. so if you have <script src="file1"> then <script src="file2"> in your html file, and you put x = 10 in the first file and use it in the second, you will have no problems. If you are using node.js, I can post a solution for that as well, just let me know.

(btw if you put x = 10 in the second file and reference it from the first it will throw an error)

There are ways of avoiding this, such as using a document.ready function or wrapping things in functions and then calling them at the end. You need to make sure that functions and variables are created before being used (this is a common mistake beginners make and are confused by)

Upvotes: 0

fjoe
fjoe

Reputation: 1160

It is hard to say without some code to reference but maybe just a global variable with a check if its null.

var myJsonString = null;

function one () {
    var jsonString = "[]";
    myJsonString = jsonString;
}

function two () {
    //string not set so bail
    if (myJsonString === null) { return; }
}

Upvotes: 0

Related Questions