如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1690字,纯文字阅读大概需要3分钟。
内容图文
![如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?](/upload/InfoBanner/zyjiaocheng/729/92fc48e56401400792764ec3b442d7f3.jpg)
我可能会遗漏一些明显的东西,但是我怎么能重写这段代码以便它不需要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中存储和访问ajax数据?全部内容,希望文章能够帮你解决如何在不使用全局变量的情况下在javascript中存储和访问ajax数据?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。