我在Web应用程序的根目录http://localhost/foo.txt中有一个文本文件,我想将其加载到javascript .. groovy中的变量中,我可以这样做:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
如何在javascript中获得类似的结果?
我在Web应用程序的根目录http://localhost/foo.txt中有一个文本文件,我想将其加载到javascript .. groovy中的变量中,我可以这样做:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
如何在javascript中获得类似的结果?
Answers:
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在同一域上时,这才起作用。如果它在其他域中,则同源策略将阻止您读取结果。
if (client.readyState === 4){ }
client.onloadend并仅获取完整的数据
client.readyState属性值。我对此表示不满,直到人们不会阅读评论来发现答案只是部分正确。
这是我在jQuery中做的事情:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
file://ie:在本地对其进行测试,则此方法无效file:///example.com/foo.html。Firefox抱怨语法错误并且Chrome被阻止,因为Firefox将其视为跨域请求。
dataType参数,它将使用纯数据,请参阅api.jquery.com/jQuery.get/
http://...部分,因为它位于同一域中,它将起作用,例如jQuery.get("foo.txt", ...)。
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
response.ok在代码中放置一些(或等效内容)?我对的经验不是很丰富fetch,所以我不知道设置它的确切位置。
如果只需要文本文件中的常量字符串,则可以将其包含为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 。
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');
这几乎可以在所有浏览器中使用:
var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();
此外,还有新的FetchAPI:
fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )
使用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/。
如果您的输入被构造为XML,则可以使用该importXML函数。(有关更多信息,请参见quirksmode)。
如果不是XML,并且没有用于导入纯文本的等效功能,则可以在隐藏的iframe中打开它,然后从那里读取内容。