javascript - $.each and $.getJSON methods to array of links -


after converting array of names in array of url links users online , offline , names closed accounts ["https://link_1","https://link_2",name(for closed account),"https//link_3",...] through $.map method , the .getjson within that.

i try apply $.each method condition within again, if element starts "http" applied .getjson method work json object of element (link) , add html values of properties( e.g. html+=json.name); if element doesn't start "http" add value of element (e.g. html+=value). doesn't work; html variable takes index , value within jquery.each, not json object of nested .getjson method. lost?

 channels=["https://link1","https://link2","name(for closed account)",....]; var html="";  $.each(channels,function(index,value){      // elements links     if(value.substring(0,4)=="http"){          $.getjson(value,function(json){           html+=json.name;       });     }        // elements not links     else {       html+= value;     }  }); 

your json requests return asynchronously, if test value of html right below code provided, none of json requests have returned, corresponding response data missing in html.

instead, need use callback function of json request keep track of how many replies have received, , when have of them, html.

here suggested code:

function buildhtml(channels, ready) {     // use array, can store each response in corresponding slot     var html = [];     // keep count of replies still need     var count = channels.length;     $.each(channels,function(index, value){         // elements links         if(value.substring(0,4)=="http"){             $.getjson(value,function(json){                 html[index] = json.name;                 count--;                 if (count == 0) {                     // done, notify caller:                     if (ready) ready(html.join(''));                 }           });         }            // elements not links         else {             html[index] = value;             count--;         }     });     if (count == 0) { // true if there no http entries:         // done, notify caller:         if (ready) ready(html.join(''));     } }  channels=["https://link1","https://link2","name(for closed account)",....]; // provide call function called when html complete: buildhtml(channels, function (html) {     console.log('the returned html is: ' + html); }); 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -