【发布时间】:2011-05-25 14:46:25
【问题描述】:
我已将一些主题 URL 密钥保存到 localStorage,现在想循环访问它们以获取每个主题的内容。
// Walk through saved subjects
allSubjects = JSON.parse(localStorage.getItem('subjects'));
var i = 0;
var ii = 0;
var xhrIn = [];
for (i = 0; i < allSubjects.length; i++) {
xhrIn[i] = new XMLHttpRequest();
xhrIn[i].open("GET", "https://myserver.com/" + allSubjects[i], true);
xhrIn[i].onreadystatechange = function() {
if (xhrIn[ii].readyState == 4) {
console.log(xhrIn[ii].responseText);
percents = Math.floor((((ii+1)/allSubjects.length)*100));
$("div#status").text('Downloading... ' + percents + '%');
// Final phase
if ((ii+1) == allSubjects.length) {
$("div#status").text("All downloaded and saved in console.");
}
ii++;
}
};
xhrIn[i].send();
}
}
这不起作用,它只捕获第一个 URL,之后我的控制台日志显示所有其他 URL 都已联系,但从未执行 xhrIn[i].onreadystatechange 闭包。
这对我来说似乎有点神奇……谁能解释一下这种行为?
【问题讨论】:
-
订单不保证,所以里面的东西是错误的。
标签: javascript google-chrome-extension lifecycle xmlhttprequest