异步XMLHttp请求不能在for循环中使用?

时间:2019-06-16 23:31:03

标签: javascript ajax asynchronous xmlhttprequest

for循环中的多个XML请求在同步调用中可以正常工作,但是在方法异步时无法获取相同的数据

我从youtube获得了16个频道的数据,但处于同步模式。而且,这似乎已经过时了。

var ga;
var test = [];
var routeRequestURL;
var routeRequest;



for(i=0;i<haciko.length;i++){
var uz;
var vie;
var hr = haciko[i].querySelector("a").getAttribute("href");
//console.log(hr);
if(hr.search("user")>0){
var nane = hr.substring(29,hr.length);
if(nane.charAt(nane.length-1)=='/' ||nane.charAt(nane.length-1)==' ')nane = nane.substring(0, nane.length - 1);
uz = "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername="+nane+"&key=[API-KEY]";
}
else{
var nane = hr.substring(32,hr.length);
if(nane.charAt(nane.length-1)=='/' ||nane.charAt(nane.length-1)==' ')nane = nane.substring(0, nane.length - 1);
uz = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id="+nane+"&key=[API-KEY]"; 
}


routeRequestURL = uz

//console.log(uz);
routeRequest = new XMLHttpRequest();
routeRequest.open("GET", routeRequestURL,false);
routeRequest.onreadystatechange = (function(i) { return function() {

    if(routeRequest.readyState == 4 && routeRequest.status == 200) {
test.push(JSON.parse(routeRequest.responseText).items[0].statistics.viewCount);
       // ga = JSON.parse(routeRequest.responseText).items[0].statistics.viewCount;


     }
}})(i);
routeRequest.send();

haciko[i].querySelector(".birebir-count").innerText = test[i].toLocaleString();
//test.push(JSON.parse(routeRequest.responseText).items[0].statistics.viewCount);

}```

0 个答案:

没有答案