微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?

我可能会遗漏一些明显的东西,但是我怎么能重写这段代码以便它不需要theVariable作为全局变量

<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字符串,当您将鼠标悬停在页面的各个部分时,将访问该数据.我最终使用了几个全局变量,这些变量工作得很好但是很乱,我想知道是否有更好更优雅的方法呢?

解决方法:

我会做的事情如下:

<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 [无论如何].

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐