且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 url 中的 txt 文件中获取文本

更新时间:2023-02-23 20:02:03

使用 Fetch API.

一起玩 jsfiddle.net.

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 示例,它将获取与存储和展示结果分开.

Here's a smaller ES6 example that separates fetching from storing and showing off the result.

fetch('https://fiddle.jshell.net/robots.txt')
  .then((response) => response.text().then(yourCallback));

function yourCallback( retrievedText ) { /* . . . */ }

已经全面采用.

您不必等待.大多数人不会.你不应该.
GitHub 提供了无法升级的 polyfill.

You don't have to wait. Most people don't. You shouldn't.
GitHub provides a polyfill of those who can't upgrade.

fetch 有什么比 XHR 更好的地方?... 大量.

What's better about fetch than XHR? ... Lots.