[英]fileReader.readAsText() javascript: result not displayed
I am working on a html project in which the user uploads a txt file whose content is further processed and the result shown. 我正在处理一个html项目,其中用户上传了一个txt文件,其内容将得到进一步处理并显示结果。 The upload and processing step works fine but somehow the result is never shown.
上载和处理步骤工作正常,但从某种程度上讲,结果从未显示出来。 The (for me) confusing part is that if I add an alert() between processing and result presentation, the result is then displayed correctly.
(对我而言)令人困惑的部分是,如果我在处理和结果表示之间添加了alert(),则结果将正确显示。
Is this a known issue that I am missing? 这是我所缺少的已知问题吗?
In the code example bellow, if you remove the commentary on the alert(), the result is displayed correctly in the "demo" paragraph. 在下面的代码示例中,如果删除了alert()上的注释,则结果将在“演示”段落中正确显示。 But without it, nothing is shown.
但是没有它,什么也没显示。
I'd be grateful for either an explanation of my mistake or an alternative solution. 对于我对错误的解释或替代解决方案,我将不胜感激。
Thank you very much! 非常感谢你!
function myFunction() { var x = document.getElementById("file"); var textFromFileLoaded = ""; if (x.value != "") { // text upload var file = x.files[0]; var fileReader = new FileReader(); fileReader.onload = function(fileLoadedEvent) { textFromFileLoaded = fileLoadedEvent.target.result; } fileReader.readAsText(file, "UTF-8"); } //alert("somth"); //HERE document.getElementById("demo").innerHTML = textFromFileLoaded; return true; }
Select a file to upload: <input type="file" id="file" size="50" accept="image/*"> <button onclick="myFunction()">button</button> <p id="demo"></p>
You should put document.getElementById("demo").innerHTML = textFromFileLoaded;
您应该将
document.getElementById("demo").innerHTML = textFromFileLoaded;
inside the onload function 在onload函数中
fileReader.onload = function(fileLoadedEvent) {
textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("demo").innerHTML = textFromFileLoaded;
}
Filereader is asynchronous so when you add the alert you give your code enough time to call onload before you add the text into the demo element. Filereader是异步的,因此当您添加警报时,在将文本添加到demo元素之前,您有足够的时间调用代码onload。 Without the alert
textFromFileLoaded
is not set (from the onload function) when you add it to the demo element 当您将其添加到演示元素中时,没有设置警告
textFromFileLoaded
(通过onload函数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.