xmlhttprequest - Javascript variable doesn't maintain its value outside of inner function -
this question has answer here:
i'm trying write function iterate through api's database using xmlhttprequest()'s. once response value , add 'info' div in html, want append value line. however, when console.log(line), prints out nothing, had instantiated in function before loop. here's code:
var line = ''; document.getelementbyid('info').innerhtml = ''; var xhr = []; (i = 1; < 11; i++){ (function (i){ xhr[i] = new xmlhttprequest(); url = "http://pokeapi.co/api/v2/item-category/" + i; xhr[i].open("get", url, true); xhr[i].onreadystatechange = function () { if (xhr[i].readystate == 4 && xhr[i].status == 200) { var response = json.parse(xhr[i].responsetext); document.getelementbyid('info').innerhtml += response.name + '<br>'; line += response; } } xhr[i].send(); })(i); } console.log(line);
Comments
Post a Comment