dan*_*anb 137 javascript
我在我的网络应用程序http://localhost/foo.txt的根目录中有一个文本文件,我想将它加载到javascript中的变量..在groovy中我会这样做:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
Run Code Online (Sandbox Code Playgroud)
如何在javascript中获得类似的结果?
Edw*_*ang 132
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位于同一个域时,这才会起作用.如果它位于不同的域中,则同源安全策略将阻止您读取结果.
dan*_*anb 85
这是我在jquery中的表现:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
Run Code Online (Sandbox Code Playgroud)
Vic*_*Vic 29
使用Fetch:
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Eri*_*ahl 22
如果您只想从文本文件中获取常量字符串,则可以将其包含为JavaScript:
// This becomes the content of your foo.txt file
let text = `
My test text goes here!
`;Run Code Online (Sandbox Code Playgroud)
<script src="foo.txt"></script>
<script>
console.log(text);
</script>Run Code Online (Sandbox Code Playgroud)
加载后,JavaScript可以访问从文件加载的字符串.`(反引号)字符开始和结束模板文字,允许文本块中的"和"字符.
当您尝试在本地加载文件时,此方法很有效,因为Chrome不允许在带有该file://方案的网址上使用AJAX .
gma*_*man 14
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
Run Code Online (Sandbox Code Playgroud)
注意await只能在async函数中使用。一个更长的例子可能是
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
Run Code Online (Sandbox Code Playgroud)
要记住的一件事是Javascript在客户端上运行,而不是在服务器上运行.您无法在Javascript中真正从服务器"加载文件".会发生什么是Javascript向服务器发送请求,服务器发回所请求文件的内容.Javascript如何收到内容?这就是回调函数的用途.在爱德华的案例中,就是这样
client.onreadystatechange = function() {
Run Code Online (Sandbox Code Playgroud)
在danb的情况下,它是
function(data) {
Run Code Online (Sandbox Code Playgroud)
只要数据恰好到达,就会调用此函数.jQuery版本隐式使用Ajax,它只是通过将代码封装在库中来简化编码.
这几乎可以在所有浏览器中使用:
var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();
Run Code Online (Sandbox Code Playgroud)
此外,还有新的FetchAPI:
fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406148 次 |
| 最近记录: |