如何使我的变量包含在此函数中?

时间:2014-03-21 21:37:32

标签: javascript jquery

我正在尝试存储接收JSON数据的函数中包含的变量的数据。此变量通常具有存储在其中的json数据。出于测试目的,我只是为变量提供了一个对象数组,而不是存储在变量中返回的实际JSON数据。变量是window.mySHows,正如你所看到的,这是我试图通过在变量前面使用“window”来创建全局的变量。在这个例子中,我使用一个对象数组来表示这个变量将具有的JSON数据。问题是,我无法在它所处的功能之外达到这个变量。我试图让它变得全局,但那不起作用。下面是我的代码:(我也使用角度JS)

 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");

 });

1 个答案:

答案 0 :(得分:1)

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