How to store and access ajax data in javascript without using global variables ?
Posted
by mike_t2e
on Stack Overflow
See other posts from Stack Overflow
or by mike_t2e
Published on 2010-04-03T08:35:09Z
Indexed on
2010/04/03
8:43 UTC
Read the original article
Hit count: 262
I may be missing something obvious here, but how could I rewrite this code so that it doesn't need the theVariable to be a global variable ?
<script language="javascript">
theVariable = "";
function setValue() /* called on page load */
{
/* make ajax call to the server here */
theVariable = "a string of json data waiting to be eval()'d";
}
function getValue()
{
alert(theVariable);
}
</script>
<input type="button" onClick="javascript:getValue()" value="Get the value">
In my actual situation, the setValue function makes an ajax call to the server, receives a json string and the data from that is accessed when you mouseover various parts of the page. I end up using several global variables which works fine, but is messy and I'd like to know if there's a better and more elegant way of doing it ?
© Stack Overflow or respective owner