使用异步 XMLHttpRequest 加载 XML 文件数组
我想加载 XML 文件数组,并将它们存储在数组中。
代码示例:
var src = [ "a", "b", "c", "d" ];
var dest = {};
for (var i in src) {
var req = new XMLHttpRequest();
req.open("GET", src[i], true);
req.onreadystatechange = function(aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
dump(i + "\n");
dest[i] = req.responseXML;
}
}
}
req.send(null);
}
但是,转储结果始终是
3
3
3
3
说明callback中引用的i
始终是外层i
,导致XML文件无法正确存储。
那么,如何解决这个问题呢?我们有大约 50 个 XML 文件需要加载,并且一一加载它们是不可接受的。
谢谢。
I want to load an array of XML files, and store them in an array.
Code example:
var src = [ "a", "b", "c", "d" ];
var dest = {};
for (var i in src) {
var req = new XMLHttpRequest();
req.open("GET", src[i], true);
req.onreadystatechange = function(aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
dump(i + "\n");
dest[i] = req.responseXML;
}
}
}
req.send(null);
}
However, the dump result is always
3
3
3
3
It shows that the i
referenced in callback is always the outer i
, so the XML files cannot be stored correctly.
So, how to solve this issue? We have about 50 XML files to load and loading them one by one is not acceptable.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
for..in
循环数组。使用普通的for
循环。i
将始终引用您循环的数组的最后一个元素。它们都引用了相同i
。您可以通过使用返回函数的立即执行函数来解决此问题(从而捕获i
的值)。req
的引用,否则它将始终引用最后生成的 XMLHttpRequest(与i
的原因相同)。所以一种解决方案是:
@Spiny Norman 的解决方案可能更具可读性;)
for..in
to loop over arrays. Use a normalfor
loop.i
will always refer to the last element of the array you looped over when the functions you created are executed. They all have a reference to the samei
. You can solve this by using an immediately executing function that returns a function (thus, capturing the value ofi
).req
, otherwise it will always refer to the last generated XMLHttpRequest (the same reason as fori
).So one solution would be:
@Spiny Norman's solutions might be more readable ;)
你可以这样做:
顺便说一句,你似乎总是加载相同的 xmlfile,但我确信这在你的实际代码中是不同的;)
You could do something like this:
By the way, it seems you're always loading the same xmlfile, but I'm sure this is different in your actual code ;)