Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - 如何将文本文件的内容加载到javascript变量中?(How do I load the contents of a text file into a javascript variable?)

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:(我在我的网络应用程序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中获得类似的结果?)   ask by danb translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

XMLHttpRequest, ie 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.(但是,正常情况下,XMLHttpRequest并非在所有平台上都可用,因此一些软件已经完成。) Once again, your best bet is to use an AJAX framework like jQuery.(再一次,最好的办法是使用像jQuery这样的AJAX框架。) One extra consideration: this will only work as long as foo.txt is on the same domain.(一个额外的考虑因素:只有当foo.txt位于同一个域时,这才会起作用。) If it's on a different domain, same-origin security policies will prevent you from reading the result.(如果它位于不同的域中,则同源安全策略将阻止您读取结果。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...