Storing result of AJAX in pure Javascript -




this question has answer here:

i learning basics of ajax, , trying store result of call in variable. have data.txt file object:

[ { "id": "5688","name": "  jorge luis borges"}, { "id": "5799","name": "  lewis carroll"} ] 

and calling call:

var object = "no object"; function requestfunction(url){     var request = new xmlhttprequest();     request.open("get", url, true);     request.addeventlistener("load", function() {         object = this.response;     });     request.send(null);     return object; }; console.log(requestfunction("data.txt")); 

i don't know why, result = this.response doesn't affect variable want store result, , console outputs original value: no object.

any idea why?


edit: have been reading fantastics responses in how return response asynchronous call?, , updated function include callback that, when called, output result:

function requestfunction(url){     var request = new xmlhttprequest();     request.open("get", url, true);     request.addeventlistener("load", function() {         outputfunction(this.response); // callback     });     request.send(null); };  // callback function outputfunction(a){     console.log(a); };  requestfunction("data.txt"); 

it works. now, inside callback, want store result in variable, , use outside function. like:

// callback var storedobject = "empty"; function outputfunction(a){     storedobject = a;     return storedobject; }; 

but again, doesn't works. ¿is because same reason previous code?

request.addeventlistener("load", function() {         object = this.response;     }); 

is called asynchronously

object = this.response; 

would updated later, code

console.log(requestfunction("data.txt")); 

doesn't wait finish updating, hence prints orignal value





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

python - Read npy file directly from S3 StreamingBody -