javascript - Storing XMLHttpRequest.responseText into variable -


this question has answer here:

not familiar xmlhttprequests, using cross-origin function in google chrome extensions. works great (i can confirm appropriate data need), can't seem store within 'response' variable.

i'd appreciate help.

function getsource() {     var response;     var xmlhttp;      xmlhttp=new xmlhttprequest();     xmlhttp.onreadystatechange=function() {       if (xmlhttp.readystate==4 && xmlhttp.status==200)         {              response = xmlhttp.responsetext;                  //im correctly set here         }         //i'm still set here     }     //all of sudden i'm undefined.      xmlhttp.open("get","http://www.google.com",true);     xmlhttp.send();      return response;  } 

the onreadystatechange function asynchronous, not stop later code running before function has completed.

for reason, you're going entirely wrong way. typically in asynchronous code, callbacks employed able called when onreadystatechange event fires, know able retrieve response text @ time. example, case of asynchronous callback:

function getsource(callback) {     var response, xmlhttp;      xmlhttp = new xmlhttprequest;     xmlhttp.onreadystatechange = function () {       if (xmlhttp.readystate === 4 && xmlhttp.status === 200 && callback) callback(xmlhttp.responsetext);     }      xmlhttp.open("get", "http://www.google.com", true);     xmlhttp.send(); } 

think of using settimeout, asynchronous. following code not hang 100 000 000 000 000 seconds before ending, rather end immediately, , wait timer run function. then, assignment useless, isn't global , nothing else in scope of assignment.

function test() {   var a;     settimeout(function () { = 1; }, 100000000000000000); //high number example     return a; // undefined, function has completed, settimeout has not run yet     = 1; // it's doing after return, has no effect } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -