当我转到这样的 url 时:http://my.url.com/file.txt,浏览器显示文本。
我想要一个执行以下操作的简单 javscript 命令:
1. 转到网址
3. 获取屏幕上显示的文字
4. 将其存储在变量中以供进一步处理
类似的东西
var url = http: //my.url.com/file.txt;
//这里有一些代码指向url
//一些代码获取所述信息并做类似的事情:
var fileInfo = ---content of file.txt---
请注意,我从 txt 文件中查找的信息位于 html 标记中
<p>Text I need in Variable</p>
如有任何帮助,我们将不胜感激!
谢谢!
最佳答案
Use the Fetch API.
var url = 'https://fiddle.jshell.net/robots.txt';
var storedText;
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
done();
});
});
function done() {
document.getElementById('log').textContent =
"Here's what I got! \n" + storedText;
}
这是一个较小的 ES6 示例,它将获取与存储和显示结果分开。
fetch('https://fiddle.jshell.net/robots.txt')
.then((response) => response.text().then(yourCallback));
function yourCallback( retrievedText ) { /* . . . */ }
Adoption is already across the board.
您无需等待。大多数人没有。你不应该。
GitHub provides a polyfill of those who can't upgrade.
fetch 比 XHR 有什么优势? ... Lots .
关于javascript - 从 url 中的 txt 文件中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758031/