首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使包含在此函数中的变量成为全局变量?

如何使包含在此函数中的变量成为全局变量?
EN

Stack Overflow用户
提问于 2014-03-22 05:37:32
回答 1查看 42关注 0票数 0

我正在尝试存储来自接收JSON数据的函数中包含的变量的数据。此变量通常将返回的json数据存储在其中。出于测试目的,我并没有在变量中存储返回的实际JSON数据,而是只向变量提供了一个对象数组。这个变量是window.mySHows,正如你所看到的,这是我试图通过在我的变量前面使用"window“使其成为全局的变量。在本例中,我使用了一个对象数组来表示这个变量将拥有的JSON数据。问题是,我不能在它所在的函数之外到达这个变量。我试着让它变得全球化,但这不起作用。下面是我的代码:(我也在使用angular JS)

代码语言:javascript
运行
复制
 function getStuff(num, onContents){
 $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://catholic.com/api-radio/' + num) + '&callback=?', function(data){
   //call the oncontents callback instead of returning
   onContents(data.contents);
 });
 }

 //when calling getstuff, pass a function that tells what to do with the contents
 getStuff(6387, function(contents){
 var res = (contents);
 //I'm not going to store res in window.myShows, instead I'm adding the test JSON
 window.myShows = [{
    "from": "Steve Jobs",
    "subject": "I think I'm holding my phone wrong :/",
    "sent": "2013-10-01T08:05:59Z"
 },{
    "from": "Ellie Goulding",
    "subject": "I've got Starry Eyes, lulz",
    "sent": "2013-09-21T19:45:00Z"
 },{
    "from": "Michael Stipe",
    "subject": "Everybody hurts, sometimes.",
    "sent": "2013-09-12T11:38:30Z"
 },{
    "from": "Jeremy Clarkson",
    "subject": "Think I've found the best car... In the world",
    "sent": "2013-09-03T13:15:11Z"
 }];

 });


 //$scope.shows does not get the data from window.myShows
 $scope.shows = window.myShows;

 // -- Native navigation
 steroids.view.navigationBar.show("Show index");

 });
EN

回答 1

Stack Overflow用户

发布于 2014-03-22 05:40:25

这是因为$scope.shows = window.myShowswindow.myShows = [{...}];之前执行,因为后者在AJAX响应中,所以在$scope.shows变量赋值时,window.myShows是未定义的。我会使用Deferred object

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22569979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档