javascript - AJAX callbacks when getting multiple XML files -
i'm trying better understanding of how callbacks work.
in example, want 2 or more xml files using ajax, extract content need them, , store data in array outside of ajax call. want use "dataext" array plot google chart, getting hung implementing callbacks properly. guess brain isn't big enough yet!
here's code snippet.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> // list of xml files. var xmlfeed = ['rss-feed1.xml', "rss-feed2.xml"]; // array store each "datastring" each xml file. var dataext = []; for(var = 0; < xmlfeed.length; i++) { $.ajax({ type: "get", datatype: "xml", async: true, url: xmlfeed[i], contenttype: "text/xml; charset=utf-8", success: function(xml){ var content = $(xml).find("content"); var datastring = (content.text()); console.log(datastring); // need push "datastring" "dataext" array. // dataext = dataext.push(datastring); <-- doesn't work } }) // close ajax } // close loop console.log(dataext[0]); console.log(dataext[1]); </script>
when make ajax request, call $.ajax() returns immediately. not wait around content come on network. in example, console.log() statements being called before callbacks have been completed.
what want single callback gets executed once data need various requests has been fetched. need sort of synchronization between various ajax calls you're doing. jquery alone doesn't support well.
you can roll yourself. however, common enough design problem whole libraries have been written handle it.
do googling on promise pattern. once you've done that, have @ q library, 1 of several implementations of pattern. have done of hard work of synchronizing multiple ajax requests you.
example:
function xmlpromise(name) { return q.promise(function (resolve, reject, notify) { $.ajax({ type: "get", datatype: "xml", async: true, url: name, contenttype: "text/xml; charset=utf-8" }) .done(function (data) { resolve(data); }).fail(function () { reject(); }); }); }; var promises = [ xmlpromise('1.xml'), xmlpromise('2.xml') ]; var results = []; q.allsettled(promises).then(function(responses) { console.log(responses[0].value); console.log(responses[1].value); results.push(responses[0].value); results.push(responses[1].value); });
in example, xmlpromise() function creates promise object based on url want fetch. promise represents unit of work completed @ time in future. when ajax call create in promise returns successfully, calls resolve() method lets q know promise has been fulfilled, , data ready use.
once promises constructed, pass array of them q.allsettled(), fires off requests. because these requests asynchronous, executed in parallel. once of promises either resolved or been rejected, q call function pass then() method, , pass in results of ajax calls.
Comments
Post a Comment