I'm trying to populate an array in JavaScript using an anonymous function in the jQuery getJSON()
function as follows.
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
var links = [];
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
});
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
But, when I hit the for loop, the links array shows up empty. What's going on here?
Try that :
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
var links = [];
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
});
Your loop was probably executed before your callback ;)
That's because $.getJSON
is an asynchronous method. The code execution continues even after $.getJSON
and reaches the for
loop, by which time, your async request hasn't completed yet. You should move the loop within $.getJSON
.
此jsFiddle http://jsfiddle.net/cArYg/2/显示了在getJson回调之前发生的迭代
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.