-2

I can't figure how to loop through an array of urls and pass them to getJSON, to finally return the new array of datas.

var data_num=[];
$.each(arr_urls, function( index, value ) {          
    $.getJSON(arr_urls[index], function (data) {});
    data_num.push(data);
});
alert(data_num);
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Nirs
  • 45
  • 8
  • 2
    You have to `push` the `data` *inside* of the callback. – str Jun 02 '16 at 13:36
  • I did it too originally but it doesn't seem to work. – Nirs Jun 02 '16 at 13:38
  • 1
    Yes it works. Another problem of your code is that you `alert` the array *before* the callback is executed. So `data_num` is always empty when you run it. – str Jun 02 '16 at 13:38
  • 1
    If order of response doesn't matter, use http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when But you have firstly to understand how async call works – A. Wolff Jun 02 '16 at 13:40
  • 1
    Also related: http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done . There are a billion questions about jQuery, Ajax and async. Please use the search. – Felix Kling Jun 02 '16 at 13:49
  • My bad for not allowing the response to arrive at alert time. – Nirs Jun 02 '16 at 13:52

2 Answers2

1
var data_num=[];
$.each(arr_urls, function( index, value ) {

  $.getJSON(arr_urls[index], function (data) {
      data_num.push(data);
      alert(data_num);
  });
});

Put your pusher and alert in the callback like this.

Jon Crawford
  • 193
  • 11
-1

Why can't you just do:

var jsonData = JSON.stringify(arr_urls);
Michael Ciba
  • 561
  • 3
  • 6