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

时间:2008-10-13 01:57:14

标签: javascript

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

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

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

9 个答案:

答案 0 :(得分:127)

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在同一个域上时才会有效。如果它位于不同的域中,则同源安全策略将阻止您读取结果。

答案 1 :(得分:81)

这是我在jquery中的表现:

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

答案 2 :(得分:22)

如果您只想从文本文件中获取常量字符串,则可以将其包含为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可以访问从文件加载的字符串。 `(反引号)字符开始和结束template literal,允许文本块中的“和”字符。

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

答案 3 :(得分:15)

更新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

答案 4 :(得分:9)

Update 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');

答案 5 :(得分:8)

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

    client.onreadystatechange = function() {

而在danb的情况下,它是

 function(data) {

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

答案 6 :(得分:6)

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

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

答案 7 :(得分:1)

使用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/

答案 8 :(得分:-4)

如果您的输入结构为XML,则可以使用importXML函数。 (更多信息here at quirksmode)。

如果它不是XML,并且没有用于导入纯文本的等效函数,则可以在隐藏的iframe中打开它,然后从那里读取内容。

相关问题