Jump to content

A question about global variable?


tinfanide
 Share

Recommended Posts

<html><!--php_json.php--><head><script src="json2.js"></script><script src="php.js"></script><script>ajax("php_json.json",function(){oJSON = JSON.parse(xmlhttp.responseText);sJSON = JSON.stringify(oJSON);/*put it hereokay*/});// here, the variable sJSON is undefinedajax("php.php?json="+sJSON,function(){  alert(xmlhttp.responseText);   });//</script></head><body></body></html>

// php.jsfunction ajax(source,func){xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") ? new ActiveXObject("Msxml2.XMLHTTP") : null ;xmlhttp.onreadystatechange = function(){  (xmlhttp.readyState == 4 && xmlhttp.status == 200)   ? func() : null ;  }xmlhttp.open("GET",source,true);xmlhttp.send();}

wanna ask how to extend the scope of the variable sJSON to be global?

Link to comment
Share on other sites

declare it outside of the function scope. i.e.

<script>var oJSON, sJSON;..

however, if you plan on using the value of sJSON across two asynchronous requests (with the second being dependent on the first), you would probably want to make the second AJAX request as part of the callback function of the first. (at that point it won't need to be global though).

Edited by thescientist
Link to comment
Share on other sites

You can also declare it as window.sJSONAll global variables are properties of the window object. Even then, it's not going to be set until the first AJAX request is finished, so you should only send the second request when the first one returns.

Link to comment
Share on other sites

actually, I am mistaken. The variables were already global (because you never used var in front of it), the issue was you were trying to use the value of sJSON in the second request before the first request completed and set its value.

Link to comment
Share on other sites

declare it outside of the function scope. i.e.
<script>var oJSON, sJSON;..

however, if you plan on using the value of sJSON across two asynchronous requests (with the second being dependent on the first), you would probably want to make the second AJAX request as part of the callback function of the first. (at that point it won't need to be global though).

How's a callback function like?Is it to check the readyState and status of the first AJAX request before going to the second one?
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
 Share

×
×
  • Create New...