How to store and access ajax data in javascript without using global variables?

Maybe I am missing something obvious, but how can I rewrite this code so that it does not need the variable 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 real situation, the setValue function makes an ajax call to the server, receives a json string and the data accessed when you hover over different parts of the page. I end up using a few global variables that work fine, but randomly, and I would like to know if there is a better and more elegant way to do this?

+3
source share
4 answers

I would do something like:

<script language="javascript">
var myApp = function () {

    /* theVariable is only available within myApp, not globally 
     * (unless you expose it) 
     */
    var theVariable = "";  

    /* called on page load */
    var setValue = function setValue(){

       /* make ajax call to the server here */
       theVariable = "a string of json data waiting to be eval()'d"; 

    };

    var getValue = function getValue() {

        alert(theVariable);

        // call useless private function
        pFunc();

    };

    var pFunc = function pFunc(){
        // this is a hypothetical private function
        // it only here to show you how to do it
        // in case you need it

    };

    // now expose anything you need to be globally available
    // basically anything that will be called outside of myApp

    return { setValue: setValue, getValue: getValue}; 
}(); 
</script>     


<input type="button" onClick="myApp.getValue()" value="Get the value">

- - myApp.setValue(), .

:

return this;

( )...

myApp.whatever myApp [whatever].

+3

jQuery ( ajax), .data(), /.

javascript , /id, ,

document.myData = 'xyz';

, , closure.

+2

:

<script type="text/javascript">
function setValue() /* called on page load */
{
    /* make ajax call to the server here */
    var theVariable = "a string of json data waiting to be eval()'d"; /* declared with var to make it a private */
    getValue = function() /* declared without var to make it a public function */
    {
        alert(theVariable);
    }
}
</script>
+1

If you are not against one global, you can create a javascript object and save any amount of data local to the javascript object.

Here is an example:

var myData = {

variable1: '',

variable2: '',

variablen: ''

};

set the following data:

myData.variable1 = 'hello, world';

in your onclick you can call myData.variable1 to retrieve the data.

0
source

Source: https://habr.com/ru/post/1739676/


All Articles