我正在尝试存储来自接收JSON数据的函数中包含的变量的数据。此变量通常将返回的json数据存储在其中。出于测试目的,我并没有在变量中存储返回的实际JSON数据,而是只向变量提供了一个对象数组。这个变量是window.mySHows,正如你所看到的,这是我试图通过在我的变量前面使用"window“使其成为全局的变量。在本例中,我使用了一个对象数组来表示这个变量将拥有的JSON数据。问题是,我不能在它所在的函数之外到达这个变量。我试着让它变得全球化,但这不起作用。下面是我的代码:(我也在使用angular 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");
});发布于 2014-03-22 05:40:25
这是因为$scope.shows = window.myShows在window.myShows = [{...}];之前执行,因为后者在AJAX响应中,所以在$scope.shows变量赋值时,window.myShows是未定义的。我会使用Deferred object。
https://stackoverflow.com/questions/22569979
复制相似问题