【发布时间】:2018-02-10 01:36:31
【问题描述】:
[编辑] 关于回调的新问题 [编辑]
我正在尝试使用 Ajax 和 Javascript 加载一些本地文本文件,但我无法让回调正常工作。 我有我的代码大纲:
var theFiles = {
one: null,
two: null,
three: null,
four: null,
five: null,
six: null,
seven: null
};
function callback(pos,arrayofwords) {
theFiles[pos]=arrayofwords;
}
xhr = new XMLHttpRequest();
var getFiles = function(theFiles,callback) {
for (var p in theFiles) {
console.log("in getFile: " + p);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(p,xhr.responseText.split(/\r?\n/));
}
};
xhr.open("GET", p + ".txt", true);
xhr.send();
}
}
本地存储文件 one.txt、two.txt、three.txt 等... 即使 for 循环为文件中的每个键调用 open(),回调也只会执行一次。只有文件中的最后一项(七个)被填充。 我不明白为什么。
更新 在@xianshenglu 提供答案后,我发现实际上不需要回调。这也有效
var theFiles = {
one: null,
two: null,
three: null,
four: null,
five: null,
six: null,
seven: null
};
var getFiles = function(theFiles) {
for (let p in theFiles) { //var to let
let xhr = new XMLHttpRequest(); //move inside the loop
console.log("in getFile: " + p);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
theFiles[p]=xhr.responseText.split(/\r?\n/)); //no callback needed
}
};
xhr.open("GET", p + ".txt", true);
xhr.send();
}
}
【问题讨论】:
-
阅读my answer,我解释了做什么你应该做什么以及为什么。
标签: javascript ajax callback