Reputation: 367
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
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
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:
can also be solved by using $.when
.
Upvotes: 2
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