这是我的ajax请求:
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.
这是将响应(var res
)置于自调用AJAX函数之外的最佳方法吗?
有一些更整洁的方式吗?
感谢。