Friday 15 April 2011

javascript - Execute callback at end of for-loop XMLHttpRequest -



javascript - Execute callback at end of for-loop XMLHttpRequest -

this code loops through several webpages, finds links on each page, , puts links array called linksarray. i've tried execute callback when for-loop on lastly iteration (when x =45) , jquery find().each has finished searching through of lastly page links.

for reason, i'm not getting links lastly page (http://fakeurl.com/45). seems callback function executes before for-loop has gone through every webpage. why happening , how prepare it?

function linksearch(callback) { for(i = 0; <= 45; += 1) { ajaxcall(i); } var i; var linksarray = []; function ajaxcall (x) { var xhrs = new xmlhttprequest(); xhrs.open("get", 'http://fakeurl.com/' + x, true); xhrs.onload = function() { var doc = xhrs.response; var len = $(doc).length; //will used in telling when .each has gotten end of page $(doc).find("a[href^='http://linksfromeachpage.com/links']").each(function(index, element) { //below how i'm trying callback linksarray when for-loop on lastly iteration , .each has finished on lastly page thisval = $(this).val(); if (x == 45) { if(parseint(thisval) != 0) { if (index == len - 1) { if($(doc).ajaxcomplete) { callback(linksarray); } } } } var url = $(this).attr('href'); linksarray[x] = url; }); } xhrs.responsetype = 'document'; xhrs.send(); } } //and below callback called linksearch(function(thearray) { console.log(thearray); });

since question tagged jquery, here's version of code uses jquery ajax phone call , jquery promises maintain track of when done.

class="lang-js prettyprint-override">function linksearch(callback) { var i, promises = []; (i = 0; <= 45; i++) { promises.push( $.get({url:'http://fakeurl.com/' + i, datatype:'xml'}) ); } $.when.apply($, promises).then(function() { var linksarray = []; // process results here (i = 0; < arguments.length; i++){ $(arguments[i][0]) .find("a[href^='http://linksfromeachpage.com/links']") .each(function(index, element) { var url = $(this).attr('href'); linksarray.push(url); }); } callback(linksarray); }); }

javascript jquery for-loop callback xmlhttprequest

No comments:

Post a Comment