Jump to content

jQuery variable passing from <script> to another <script>


Mudsaf

Recommended Posts

Hello, i'm wondering is it possible to pass variable inside <script></script> to another <script></script> field.

 

Example i have

<script>var message = "Hello";</script><script>alert(message);</script>

I know i could add them together in this script i write, but my actual codes is separating the scripts.

Link to comment
Share on other sites

Well seems like my variable wont pass.

 

Uncaught ReferenceError: json_list is not defined

<script>$(function() {var json_list;$.getJSON('<myfile.js>', function(data) {json_list = data;});});</script>/* Later */<script>$(function() {	console.log(json_list);});</script>
Edited by Mudsaf
Link to comment
Share on other sites

or just var json_list, outside of any function() {} blocks, similar to this example from your other thread

http://w3schools.invisionzone.com/index.php?showtopic=48172#entry266827

Edited by thescientist
Link to comment
Share on other sites

<script>$(function() {var json_list;$.getJSON('../script/json/selectbox.js', function(data) {window.json_list = data;console.log(window.json_list); //Returns undefinedconsole.log(data); //Returns JSON array});});</script>
Link to comment
Share on other sites

You're still defining that variable locally, but I don't get the same results. If you define and run this function:

 

function test_func() { window.test_var = 'test'; }

 

Then outside that function, in the window scope, both test_var and window.test_var are set to "test".

Link to comment
Share on other sites

Ajax solved everything xD

var json_list;$.ajax({    url: "<myfile.js>",    dataType: 'json',    async: false,    success: function(data) {        json_list = data;    }});
Link to comment
Share on other sites

 

Ajax solved everything xD

 

no it didn't, you made a global variable like we were saying.

 

 

 

or just var json_list, outside of any function() {} blocks, similar to this example from your other thread

http://w3schools.invisionzone.com/index.php?showtopic=48172#entry266827

 

 

The lesson to learn here is how variable scope works in javascript. It's something any decent javascript developer should make it a point to learn.

http://msdn.microsof...a(v=vs.94).aspx

Edited by thescientist
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...