ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-08-27 13:20:54  阅读:133  来源: 互联网

标签:javascript json ajax global-variables


我可能会遗漏一些明显的东西,但是我怎么能重写这段代码以便它不需要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 [无论如何].

标签:javascript,json,ajax,global-variables
来源: https://codeday.me/bug/20190827/1741137.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有