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

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

问题描述:

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

I have a text file in the root of my web app http://localhost/foo.txt and I'd like to load it into a variable in javascript.. in groovy I would do this:

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

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

How can I get a similar result in javascript?

XMLHttpRequest,即AJAX,没有XML。

XMLHttpRequest, i.e. AJAX, without the XML.

你这样做的确切方式取决于JavaScript框架您正在使用,但如果我们忽视互操作性问题,您的代码将类似于:

The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

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

但是,正常情况下,XMLHttpRequest并非在所有平台上都可用,所以有些吝啬已经完成了。再一次,你最好的选择是使用像jQuery这样的AJAX框架。

Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

一个额外的考虑因素:只有当foo.txt在同一个域上时,这才会起作用。如果它位于不同的域中,则同源安全策略将阻止您读取结果。

One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.