Passing data in javascript

Asked

Viewed 97 times

2

Next, how can I pass data between two files with javascript? Example:

Archiv11:

<script>
var dado = 'dado';
</script>

Arquivo2:

<script>
alert (dado);
</script>
  • 1

    Two different HTML files?

  • Yes @bfavaretto

1 answer

1


You have to consider two things:

  • both are in the same scope (overall or common)
  • the variable is closed before the alert();. Meaning that code loaded first.

If they are not in the same scope you can use a global object for that variable to be accessible:

Archiv11:

<script>
window.dado = 'dado';
</script>

Arquivo2:

<script>
alert(window.dado);
</script>

If you are using different HTML pages you can use API of localstorage and use localstoragein view of the example with window that I hit on.

Example where writes for the localstorage: http://jsfiddle.net/hL4dzhpa/
Example where read from the localstorage: http://jsfiddle.net/qn0umtfu/

  • to create a global js variable I have to declare window.?

  • @Gustavosevero yes. The other way is omitting var in variable declaration but this is incorrect and gives headaches in debug.

  • @Sergio If the variable is declared in the global scope itself, with var, it will also be global. But global do not solve the problem posed in the question.

  • @bfavaretto truth, both :)

  • In short, I put window.variable and it can be accessed by any file of the site or system, correct?

  • 1

    @Gustavosevero yes!

  • Thanks for the help @Sergio.

  • @Gustavosevero good that I could help.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.