M
M
midarovrk2016-04-08 19:26:32
JavaScript
midarovrk, 2016-04-08 19:26:32

Displaying API information via getJSON if there is not always complete information inside?

Hello. Help solve the problem.
There is one service that provides an API via JSON
. The content looks like this:

{"gallery":{"kadr":[{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"},{"image":"инфа"}]}}


I get the info via jQuery $.getJSON Like
this:

$.getJSON('ССЫЛКА',{},function (data,b,c){
document.getElementById("kadri").innerHTML="  <img src='ссылка"+data.gallery.kadr[0].image+"'> <img src='ссылка"+data.gallery.kadr[1].image+"'> <img src='ссылка"+data.gallery.kadr[2].image+"'> <img src='ссылка"+data.gallery.kadr[3].image+"'> <img src='ссылка"+data.gallery.kadr[4].image+"'> <img src='ссылка"+data.gallery.kadr[5].image+"'> <img src='ссылка"+data.gallery.kadr[6].image+"'> <img src='ссылка"+data.gallery.kadr[7].image+"'> <img src='ссылка"+data.gallery.kadr[8].image+"'> <img src='ссылка"+data.gallery.kadr[9].image+"'> ";
});


Everything basically works fine, but if there is less content inside, for example like this:

{"gallery":{"kadr":[{"image":"инфа"},{"image":"инфа"},{"image":"инфа"}]}}


Well, i.e. if there are only 3 links to images inside or 4, well, in general, not 10 as I have written in the script, then the script does not display anything at all.

So, how to make sure that if the content is less than the script is trying to request, then it gets at least what is? And took me to the right place. What can be added to the script for implementation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2016-04-08
@midarovrk

$.getJSON('ССЫЛКА',{},function (data) {
    var html = '';
    
    data.gallery.kadr.forEach(function(element) { 
        html += '<img src="ссылка' + element.image + '">';
    })

    document.getElementById("kadri").innerHTML=html;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question