如何将文本文件的内容加载到JavaScript变量中?

我的Web应用程序http://localhost/foo.txt.的根目录中有一个文本文件,我想将其加载到JavaScript中的一个变量中..在Groovy中,我会这样做:

def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;

如何在JavaScript中获得类似的结果?

556563 次浏览

XMLHttpRequest,即不带XML的Ajax.

执行此操作的确切方式取决于您使用的JavaScript框架,但如果我们忽略互操作性问题,您的代码将类似于:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();

不过,一般来说,XMLHttpRequest并不是在所有平台上都可用,所以要做一些繁琐的工作。同样,最好的办法是使用像jQuery这样的Ajax框架。

一个额外的注意事项:只要foo.txt在同一个域中,这就会起作用。如果它在不同的域上,相同来源的安全策略将阻止您读取结果。

下面是我在jQuery中的做法:

jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});

要记住的一点是,JavaScript运行在客户机上,而不是服务器上。在JavaScript中,您无法真正从服务器“加载文件”。JavaScript向服务器发送请求,服务器发回所请求文件的内容。JavaScript如何接收内容?这就是回调函数的作用。爱德华的情况就是这样。

    client.onreadystatechange = function() {

在丹布的情况下,它是。

 function(data) {

每当数据到达时,就会调用此函数。jQuery版本隐式地使用了Ajax,它只是通过将代码封装在库中来简化编码。

当使用jQuery时,不要使用jQuery.get,例如

jQuery.get("foo.txt", undefined, function(data) {
alert(data);
}, "html").done(function() {
alert("second success");
}).fail(function(jqXHR, textStatus) {
alert(textStatus);
}).always(function() {
alert("finished");
});

你可以使用.load,它会给你一个更简洁的形式:

$("#myelement").load("foo.txt");

__,ABC0还为您提供了加载部分页面的选项,这很方便,请参阅API.jquery.com/load/

如果只需要文本文件中的常量字符串,可以将其包含为JavaScript:

// This becomes the content of your foo.txt file
let text = `
My test text goes here!
`;
<script src="foo.txt"></script>
<script>
console.log(text);
</script>

从文件中加载的字符串在加载后可供JavaScript访问。'(反勾号)字符开始和结束模板文本,允许在文本块中使用'和'字符。

当您尝试在本地加载文件时,这种方法非常有效,因为Chrome不允许使用file://方案在URL上使用Ajax.

这应该适用于几乎所有的浏览器:

var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();

此外,还有新的Fetch API:

fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )

更新2019:使用Fetch:

fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})

https://developer.mozilla.org/en-us/docs/web/api/fetch_api.

更新2020:将与Async/Await一起使用

const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);

注意,await只能用于async函数。一个更长的例子可能是

async function loadFileAndPrintToConsole(url) {
try {
const response = await fetch(url);
const data = await response.text();
console.log(data);
} catch (err) {
console.error(err);
}
}


loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');