javascript - How to access the values of local variables globally -
this question has answer here:
- how return response asynchronous call? 24 answers
i returned rsltcallback function , when call googlesearchsuggestions function , getting undefined. when console.log input parameter inside rsltcallback function it's printing output console.
var googlesearchsuggestions = function(search_keyword , element) { var parsed; var uri = 'http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=' + search_keyword; var xhr = (typeof xmlhttprequest !== 'undefined') ? new xmlhttprequest() : new activexobject(microsoft.xmlhttp); xhr.onreadystatechange = function(){ xhr.responsetype = 'xml'; if(xhr.status == 200 && xhr.readystate == 4) { var response = xhr.responsexml; var items = response.getelementsbytagname('toplevel') (var = 0 ; < items[0].childnodes.length;i++) { parsed = items[0].childnodes[i].firstelementchild.getattribute('data'); rsltcallback(parsed); } } }; xhr.open('get', decodeuri(uri), true); xhr.send(); var rsltcallback = function(input){ return input; }; return rsltcallback(); };
because have asynchronous function call in method need return parsedvalue @ later time. way called promises.
if want variable globally accessible can add window
(eg. window.parsedoutput = ...
).