2010-04-03 39 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來檢索數據。

相關問題