2010-04-03 57 views
3

我可能会在这里丢失一些明显的东西,但我怎么能重写这段代码,使它不需要theVariable成为一个全局变量?如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?

<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"> 

在我的实际情况,执行setValue功能使一个AJAX调用服务器,接收一个JSON字符串,并从当你将鼠标放置到页面的各个部分被访问的数据。我最终使用了几个可以正常工作的全局变量,但是很混乱,我想知道是否有更好更优雅的方法来实现它?

回答

3

我会做这样的事情:

<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's 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; 

或者刚出return语句完全出来(这将意味着回报这个)...

然后一切将在全球范围内可作为myApp.whatever或对myApp [任何]。

2

如果您使用jQuery(您可能用于ajax部分),您可以使用.data()方法,该方法允许您通过键/值将仲裁数据分配给文档元素。

监守JavaScript是动态类型的,你也可以按名称/ id来获取一个元素,然后将属性添加到该元素如

document.myData = 'xyz'; 

最后,你可以使用一些所谓限制你的变量范围closure

1

你可以做这样的封闭:

<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> 
0

如果你不介意有一个全球性的,你可以创建一个JavaScript对象,并存储任何数量的本地数据片段的JavaScript对象。

下面是一个例子:

变种myData的= {

变量1: '',

变量2: '',

variablen: ''

};

这样设置数据:

myData.variable1 = '你好,世界';

在您的onclick中,您可以调用myData.variable1来检索数据。