题意:如何将文本文件的内容加载到 JavaScript 变量中
问题背景:
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:
我在我的 Web 应用根目录下有一个文本文件 http://localhost/foo.txt
,我想将它加载到 JavaScript 变量中。在 Groovy 中,我会这样做
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
How can I get a similar result in javascript?
我如何在 JavaScript 中获得类似的结果
问题解决:
XMLHttpRequest, i.e. AJAX, without the XML.
使用 XMLHttpRequest,也就是 AJAX,但不涉及 XML
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:
你实现这一点的具体方式取决于你使用的 JavaScript 框架,但如果忽略互操作性问题,你的代码大致如下
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
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.
不过,通常来说,XMLHttpRequest
并非在所有平台上都可用,因此需要做一些处理。再说一遍,最好的做法是使用像 jQuery 这样的 AJAX 框架
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.
额外需要考虑的是:这只会在 foo.txt
文件与您的网页处于同一域名下时有效。如果它位于不同的域名上,同源安全策略将阻止你读取结果