开发者

getJSON wont allow array to pass through

开发者 https://www.devze.com 2023-04-13 02:38 出处:网络
function near_home(lat,long,miles) { var url = \"api_url\"; var places = []; $.getJSON(url, function(data) {
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号