问题描述
我想从文件中读取文本并在函数中返回它.因此,这是我的代码的重要部分:
I want to read a text from a file and return it in a function. So here's the important part of my code:
function getFileRequest(id, contentType, callback) {
var val = "x";
if (window.File && window.FileReader && window.FileList && window.Blob) {
var element = document.getElementById(id);
var file = element.files[0];
if(file != null) {
if(file.type.match("text/xml")){
var r;
r = new FileReader();
r.onload = function (e) {
val = e.target.result;
}
r.readAsText(file);
}
else
alert("Wrong file format");
}
} else {
alert('The File APIs are not fully supported by your browser.');
}
alert(val);
if(val == null)
return "";
else
return getRequestBody(id,contentType,val);
}
我想将文本传递给一个名为"val"的变量.但是,至少在我看来,alert(val)始终显示默认的"x",因为它可能不等待onload函数执行.我完全正确吗?那么,我如何才能访问该文本?有办法等待被执行吗?
I want to pass the text to a variable called "val". But, as it seems to me at least, alert(val) is always showing default "x" because probably it's not waiting for onload function to be executed. Am I right at all?How can I get an access to that text then? Is there a way to wait for an excecution?
推荐答案
当然,警报不在onload函数中,因此会立即调用.
Of course the alert isn't in the onload function, so it's called immediately.
您可以这样做:
var val = "x";
//... code to load a file variable
var r;
r = new FileReader();
r.onload = function (e) {
val = e.target.result;
r.readAsText(file);
alert(val);
};
您不能等待并停止执行代码,因此通常的想法是使用回调来推迟执行代码.
You cannot wait and stop the execution of your code, so the general idea is to defer it using a callback.
假设您显示的代码实际上是由两部分完成的,一个部分执行文件操作,另一部分使用它,就像这样:
Supposing the code you show is really to be done in two parts, one doing file manipulation and the other one using it, it could be like this :
function fetchVal(callback) {
var val = "x";
//... code to load a file variable
var r;
r = new FileReader();
r.onload = function (e) {
val = e.target.result;
r.readAsText(file);
callback(val);
};
}
fetchVal(function(val){
alert(val);
// use val
});
这篇关于等待文件加载(加载JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!