afcdesign
afcdesign

Reputation: 367

Combine two json calls on one <ul> list

I have the following code:

JSON call 1

$.get(url1, function(json){

  var list = '<ul>'

  $.each(json.data, function(index, value){
    list += '<li>'+value+'</li>'
  });

  list += '</ul>'

});

JSON call 2

$.get(url2, function(json){

  var list = '<ul>'

  $.each(json.data, function(index, value){
    list += '<li>'+value+'</li>'
  });

  list += '</ul>'

});

This code generates two separate unordered lists.

Can this be combined in a flexible way, so that I can merge the two lists, but not have nested JSON calls?

Upvotes: 1

Views: 295

Answers (3)

webGautam
webGautam

Reputation: 565

Maybe this will help:

var list = '<ul>'
for(var i=1;i<=2;i++){    
     $.get('http://www.example.com/page'+i, function(json){

      $.each(json.data, function(index, value){
        list += '<li>'+value+'</li>'
      }); 

    });
}
list += '</ul>'

Upvotes: 0

event_jr
event_jr

Reputation: 17707

You an use $.when to convert two promises into one:

$.when($.get(url1), $.get(url2)).done(function (res1, res2) {
  var list = '<ul>';

  var both = res1.data.concat(res2.data);
  $.each(both, function(index, value){
    list += '<li>'+value+'</li>';
  });

  list += '</ul>';

  // do something with list

})

$.when is useful to bring order to async ajax calls, while still keeping the efficiency of parallel requests. Your other question:

jQuery each with timeout

can also be solved by using $.when.

Upvotes: 2

wachme
wachme

Reputation: 2337

I don't know any way to do that without nested AJAX calls. This should work:

var list = '<ul>';

function appendItems(json) {
    $.each(json.data, function(index, value) {
        list += '<li>' + value + '</li>';
    });
}

$.get(url1, function(json) {
    appendItems(json);
    $.get(url2, function(json) {
        appendItems(json);
        list += '</ul>';
        // list is complete
    });
});

Upvotes: 1

Related Questions