使用 fetch() 返回 HTML

IT技术 javascript fetch-api
2021-02-04 15:14:12

我正在尝试获取一个文件并返回它的 HTML。然而,事情并没有我想象的那么简单。

    fetch('/path/to/file')
    .then(function (response) {
      return response.body;
    })
    .then(function (body) {
      console.log(body);
    });

这将返回一个名为 的对象ReadableByteStream我如何使用它来获取 HTML 文件内容?

如果我将 的内容更改/path/to/file为 JSON 字符串,并将上述内容更改为:

    fetch('/path/to/file')
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      console.log(json);
    });

...它正确返回JSON。我如何获取 HTML?

6个回答

您可以使用 fetch 下载 html,然后使用 DomParser API 解析它。

fetch('somePage.html')
    .then(function(response) {
        // When the page is loaded convert it to text
        return response.text()
    })
    .then(function(html) {
        // Initialize the DOM parser
        var parser = new DOMParser();

        // Parse the text
        var doc = parser.parseFromString(html, "text/html");

        // You can now even select part of that html as you would in the regular DOM 
        // Example:
        // var docArticle = doc.querySelector('article').innerHTML;

        console.log(doc);
    })
    .catch(function(err) {  
        console.log('Failed to fetch page: ', err);  
    });

很高兴答案正是我正在寻找的,即使问题没有提到写入 DOM。也相关:api.jquery.com/load
2021-04-01 15:14:12
@caffeinum - 谢谢!当您获取外部 html 页面时,它将采用纯文本格式,您无法对此做任何有意义的事情。恕我直言,自然的下一步是对该文档做一些事情,为了做到这一点,我们必须将该文本解析为 DOM。此时我们可以选择和操作该文档。我不想故意提及 jQuery,因为未来是在 vanilla JS 中的。我们都应该过渡到那个,如果我们还没有的话。
2021-04-02 15:14:12
所以附加到这个文件的脚本将运行?
2021-04-07 15:14:12
不知道,我一直在使用innerHTML
2021-04-14 15:14:12

您需要使用该.text()方法,而不是.json(). 这会将字节流转换为纯文本,浏览器可以将其解析为 HTML。

您可以使用 返回响应.text(),然后根据需要在文档中呈现页面。

function fetchHtml() {
  fetch('./file.html')
  .then((response) => {
    return response.text();
  })
  .then((html) => {
    document.body.innerHTML = html     
  });
}

使用 Promise Chaining with.then()是一种较旧的编码获取和响应的方法。更现代的方法是使用async函数,await如下所示:

async function fetchMyDocument() {      
  try {
    let response = await fetch('/path/to/file.html'); // Gets a promise
    document.body.innerHTML = await response.text(); // Replaces body with response
  } catch (err) {
    console.log('Fetch error:' + err); // Error handling
  }
}

关于问题的直接答案,(就像其他所有答案一样).text()用于代替.json()响应。

它应该是:

fetch('/path/to/file').then(function(response) {
    return response.text();
}).then(function(string) {
    console.log(string);
}).catch(function(err) {  
    console.log('Fetch Error', err);  
});