我在Web应用程序的根目录http://localhost/foo.txt中有一个文本文件,我想将其加载到javascript .. groovy中的变量中,我可以这样做:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
如何在javascript中获得类似的结果?
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在同一域上时,这才起作用。如果它在其他域中,则同源安全策略将阻止您读取结果。
这是我在jquery中做到的:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
更新2019:使用获取:
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
如果只需要文本文件中的常量字符串,则可以将其包含为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访问。`(反引号)字符在模板文字的开头和结尾,允许在文本块中同时包含“和”字符。
当您尝试在本地加载文件时,此方法效果很好,因为Chrome不允许使用该file://
方案的URL进行AJAX 。
更新2020:在异步/等待中使用提取
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');
要记住的一件事是Javascript在客户端而不是服务器上运行。您实际上无法使用Javascript从服务器“加载文件”。发生的事情是Javascript向服务器发送了一个请求,然后服务器向回发送了所请求文件的内容。Javascript如何接收内容?这就是回调函数的作用。以爱德华为例
client.onreadystatechange = function() {
在丹布的情况下
function(data) {
每当数据碰巧到达时,都会调用此函数。jQuery版本隐式使用Ajax,通过将代码封装在库中,它使编码变得更容易。
这几乎可以在所有浏览器中使用:
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) )
When working with jQuery, instead of using jQuery.get
, e.g.
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");
});
you could use .load
which gives you a much more condensed form:
$("#myelement").load("foo.txt");
.load
gives you also the option to load partial pages which can come in handy, see api.jquery.com/load/.
If your input was structured as XML, you could use the importXML
function. (More info here at quirksmode).
如果不是XML,并且没有用于导入纯文本的等效功能,则可以在隐藏的iframe中打开它,然后从那里读取内容。
文章标签:javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!