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

dan*_*anb 137 javascript

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

def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
Run Code Online (Sandbox Code Playgroud)

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

Edw*_*ang 132

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位于同一个域时,这才会起作用.如果它位于不同的域中,则同源安全策略将阻止您读取结果.

  • 此外,您可以执行`client.onloadend`并获取已完成的数据 (5认同)
  • 添加它可能是有用的,在onreadystatechange中,您可以访问XMLHttpRequest对象的readystate属性(在示例中:client.readystate)以了解状态是什么,因为onreadystatechange事件是为了加载,加载而引发的. ..所以你必须在onreadystatechange中等待client.readystate == 4才能使用client.responseText. (3认同)
  • 同源策略的解决方法是使用 jQuery 也支持的 [JSONP](http://en.wikipedia.org/wiki/JSONP)(对于客户端部分) (2认同)
  • @GameAlchemist:偶然发现了你的答案.我只想注意,在大多数浏览器中,readyState都是驼峰式的,所以代码应该是这样的:```if(client.readyState === 4){}``` (2认同)
  • 应该修改答案以包括检查`client.readyState`属性值.我一直在低估它,人们不会阅读评论,发现答案只是部分正确. (2认同)
  • 我收到错误“跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。” (2认同)

dan*_*anb 85

这是我在jquery中的表现:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您使用`file://`ie:`file:/// example.com/foo.html`在本地测试它,则不起作用.Firefox抱怨语法错误和Chrome阻止,因为它将其视为跨源请求. (6认同)
  • @Akronix 如果您省略 `http://...` 部分,因为它位于同一个域中,它会起作用,例如 `jQuery.get("foo.txt", ...)`。 (2认同)

Vic*_*Vic 29

使用Fetch:

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

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

  • 是访存是(最新)标准,而不是专有扩展。 (3认同)
  • 现在是 2019 年,fetch 是一件很美好的事情。这是所有现代浏览器的方式,包括刚刚赶上的三星互联网…… (2认同)

Eri*_*ahl 22

如果您只想从文本文件中获取常量字符串,则可以将其包含为JavaScript:

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

加载后,JavaScript可以访问从文件加载的字符串.`(反引号)字符开始和结束模板文字,允许文本块中的"和"字符.

当您尝试在本地加载文件时,此方法很有效,因为Chrome不允许在带有该file://方案的网址上使用AJAX .


gma*_*man 14

2020 年更新:将Fetch与 async/await 结合使用

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

注意await只能在async函数中使用。一个更长的例子可能是

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


atm*_*ino 8

要记住的一件事是Javascript在客户端上运行,而不是在服务器上运行.您无法在Javascript中真正从服务器"加载文件".会发生什么是Javascript向服务器发送请求,服务器发回所请求文件的内容.Javascript如何收到内容?这就是回调函数的用途.在爱德华的案例中,就是这样

    client.onreadystatechange = function() {
Run Code Online (Sandbox Code Playgroud)

在danb的情况下,它是

 function(data) {
Run Code Online (Sandbox Code Playgroud)

只要数据恰好到达,就会调用此函数.jQuery版本隐式使用Ajax,它只是通过将代码封装在库中来简化编码.


12M*_*e21 6

这几乎可以在所有浏览器中使用:

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

此外,还有新的FetchAPI:

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