javascript - Set up a for loop to fill image src's -


so i'm sending request nasa's apod api , receiving array of info, part of image url. need perform action multiple times, , wondering how set loop, or maybe function(?). html this:

<img id="apod1"> <img id="apod2"> <img id="apod3"> ...etc 

and javascript this:

// apod1 xml request var apod1url = "https://api.nasa.gov/planetary/apod?concept_tags=true"; var apod1xml = new xmlhttprequest(); apod1xml.open('get', apod1url, true); apod1xml.send(null);  // apod1 url fetch , image render apod1xml.onreadystatechange=function() {     if (apod1xml.readystate==4 && apod1xml.status==200) {         var apod1parse = json.parse(apod1xml.responsetext);         document.getelementbyid('apod1').src = apod1parse.url;         console.log(apod1parse.url);     } } 

i know can set loop like:

for (i) { stuff } 

but how feed these imgs that? clear enough.

i'm not familiar api either:

  1. request images, let browser it's work, , fill each img element or
  2. have queue , ask next image when previous done.

the first option like:

var imgids = [ 'apod1', 'apod2', 'apod3' ]; (var = 0; < imgids.length; i++) {     (function(id) {         // request          req.onreadystatechange=function() {             if (apod1xml.readystate==4 && apod1xml.status==200) {                 var apod1parse = json.parse(apod1xml.responsetext);                 document.getelementbyid(id).src = apod1parse.url;                 console.log(apod1parse.url);             }         }     })(imgids[i]); }   

the second option differs slightly. remove for , process next element of array when last request done.

var imgids = [ 'apod1', 'apod2', 'apod3' ]; function getnextimage() {     if (imgids.length == 0) {         return;     }      // request      var id = imgids.shift();     req.onreadystatechange=function() {         if (apod1xml.readystate==4 && apod1xml.status==200) {             var apod1parse = json.parse(apod1xml.responsetext);             document.getelementbyid(id).src = apod1parse.url;             console.log(apod1parse.url);              // process next             getnextimage();         }     } }  // start first image getnextimage(); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -