我有这个XMLHttpRequest并且我想要打印变量contents
...但是外部函数onload
变量contents
是“”。我如何访问函数外的变量?外部可变外部XMLHttpRequest
var xhr = new XMLHttpRequest();
var contents = ""
xhr.open("GET", fileURL);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: "application/pdf"});
var objectUrl = URL.createObjectURL(blob);
alert("sucess")
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onload = function(e) {
contents = e.target.result;
}
}
else {
alert("insucess");
}
};
xhr.send();
console.log(contents);
这似乎是适用的:http://stackoverflow.com/questions/5485495/how-can-i-take-advantage-of-callback-functions-for-asynchronous-xmlhttprequest – mariocatch
等待异步xhr完成 –
这个问题的一个变体在这里每天会被问到很多次。您的XHR呼叫是异步的。这意味着响应会在其他代码执行后的某个时候发生。因此,只有你可以可靠地使用结果的地方是INSIDE'onload'处理器或者你从那里调用的函数,并将结果传递给。你不能在'console.log()'语句的地方同步使用结果。欢迎来到异步编程的世界。你必须以不同的方式编写代码。看到你的问题被标记为许多其他解释的副本。 – jfriend00