我是JavaScript新手。我找到了一个使用javascript在StackOverflow上打开本地文件的示例。在Google搜索之后,我可以将我的Chrome设置为允许读取本地文件,然后我就可以运行该示例。但是,我想返回字符串allText
,稍后在我的脚本中使用它。但字符串在readTextFile()
之外变成undefined
。在JavaScript中打开本地文件
还有一个类似的问题here。这似乎与AJAX
的异步功能有关。我现在几乎无法理解这些行话。我只是不明白为什么在这篇文章中XMLHttpRequest.open()
的第三个参数设置为true
。
无论如何,下面是我目前的代码。我想使用allText
外部函数readTextFile()
。
<!DOCTYPE html>
<html>
<script>
function readTextFile(file)
{
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
return allText; // this is the part that goes wrong I think
}
t = readTextFile("foo.file");
document.write(t) // print out "undeifned" instead of the correct answer
</script>
</html>
可能的重复[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-调用) – Marty
你声明'allText'两次(使两个变量具有相同的名称但不同的范围),删除变量之前的第二个'var'关键字。祝你好运! –
@SantiagoHernández这是它的一部分,但它仍然不能解决异步履行竞争条件,并且在XHR请求完成之前它仍然是未定义的。 –