繁体   English   中英

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

[英]How do I load the contents of a text file into a javascript variable?

我在我的网络应用程序http://localhost/foo.txt的根目录中有一个文本文件,我想将它加载到 javascript 中的一个变量中。在 groovy 中,我会这样做:

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

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

XMLHttpRequest,即AJAX,没有XML。

您执行此操作的确切方式取决于您使用的 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);
});

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

如果您只想要文本文件中的常量字符串,您可以将其包含为 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。

2020 年更新:将Fetch与 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');

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

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) )

要记住的一件事是 Javascript 在客户端上运行,而不是在服务器上运行。 您无法真正使用 Javascript 从服务器“加载文件”。 发生的事情是 Javascript 向服务器发送请求,服务器将请求文件的内容发回。 Javascript 如何接收内容? 这就是回调函数的用途。 在爱德华的情况下,那就是

    client.onreadystatechange = function() {

在 danb 的情况下,它是

 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");

.load还为您提供了加载部分页面的选项,这可以派上用场,请参阅api.jquery.com/load/

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM