Jump to content

A question about global variable?


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 post
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 post
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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...