此代码用于读取Javascript中的.txt文件:
function readFile(fileName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(his.responseText);
return this.responseText
}
};
xhttp.open("GET", fileName, true);
xhttp.send();}
此代码将文件内容打印到控制台中。我想使用文件内容进行进一步处理。当我尝试使用JavaScript中的这两行读取内容时:
contents = readFile("data.txt");
console.log(contents);
控制台显示:未定义。我该如何解决?
您不能以同步方式使用异步结果,而是可以在Promise解析并在那里执行所需操作时调用另一个函数。
function readFile(fileName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(his.responseText);
doSomething(this.responseText); //call the function when the promise resolves and do what you want there
}
};
xhttp.open("GET", fileName, true);
xhttp.send();
}
function doSomething(text) {
//do what you want to do with the text here. 'text' here is the responseText
}