This is my ajax request:
var headingArr = [];
var firstParaArr = [];
var secParaArr = [];
var i = 0;
(function getAjx() {
var xhr = new XMLHttpRequest();
var url = 'https://api.myjson.com/bins/13vg19';
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
var res = JSON.parse(xhr.responseText);
var resLen = res.length;
for (;i<resLen;i++) {
headingArr.push(res[i].heading);
firstParaArr.push(res[i].body_one);
secParaArr.push(res[i].body_two);
}
}
else {
console.log(this.status);
}
}
xhr.send();
})();
console.log(headingArr + " " + firstParaArr + " " + secParaArr); // now we have them outside of the if scope.
Is this the best way to put the response (var res
) outside of the self-invoking AJAX function?
Is there some neater way?
Thanks.