getJSON wont allow array to pass through
function near_home(lat,long,miles) {
var url = "api_url";
var places = [];
$.getJSON(url, function(data) {
$.each(data['results'], function(i, place) {
places.push(place);
开发者_如何学运维 });
console.log(places);
});
console.log(places);
return places;
}
So the first console.log() will return the desired objects. But the second console method results in null data. I've rewritten this thing a few times over and can't seem to find reason for this madness. What am I missing?
AJAX requests are asynchronous. You need to execute all following code in a callback.
A possible solution would be this:
function near_home(lat,long,miles,cb) {
var url = "api_url";
var places = [];
$.getJSON(url, function(data) {
$.each(data.results, function(i, place) {
places.push(place);
});
cb(places);
});
}
When using the function, call it like this:
near_home(lat, long, miles, function(places) {
// your code using the returned array
});
The getJSON()
method is asynchronous so places will not have been filled at the second console.log-statement.
精彩评论