javascript - Accessing an array from with an AJAX callback function -
i'm trying use ajax call update bunch of image elements on page. list of elements update held in array , urls assign each image retrieved php page via ajax.
the code have below doesn't work because imagesarray[i]
undefined when called callback function in ajax call - due asynchronous nature of javascript presumably.
var imagesarray = document.getelementsbyclassname('swappableimages'); (i = 0; < imagesarray.length; i++) { var requesturl = "http://example.com/getanimageurl.php"; getdataviaajax(requesturl, function(data) { alert('img url=' + data.responsetext); imagesarray[i].src = data.responsetext; }); } function getdataviaajax(url, callback) { var request = window.activexobject ? new activexobject('microsoft.xmlhttp') : new xmlhttprequest; request.onreadystatechange = function() { if (request.readystate == 4) { request.onreadystatechange = donothing; callback(request, request.status); } }; request.open('get', url, true); request.send(null); } function donothing() {}
on reading around seems 1 way solve use closure
, closures i've still not managed head around , examples have found have confused me further.
so, how can update each element in array when ajax function returns?
note 'duplicate' question has been identified jquery version of question jquery specific answers. using vanilla javascript.
note: first example/approach - referred in comments - removed answer.
you may try this:
var requesturl = "http://example.com/getanimageurl.php"; (i = 0; < imagesarray.length; i++) { (function(j) { getdataviaajax(requesturl, function(data) { alert('img url=' + data.responsetext); imagesarray[j].src = data.responsetext; }); })(i); }
Comments
Post a Comment