使用 fetch() 返回 HTML

Returning HTML With fetch()

我正在尝试获取文件,return 是 HTML。然而事情并没有想象的那么简单

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

这 return 是一个名为 ReadableByteStream 的对象。我如何使用它来抓取 HTML 文件内容?

如果我把/path/to/file的内容改成JSON字符串,把上面的改成:

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

...它 return 是 JSON 正确的。我如何获取 HTML?

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

您可以使用 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);  
    });

应该是:

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

您可以 return 回复 .text(), 然后根据需要在文档中呈现页面。

function fetchHtml() {
  fetch('./file.html')
  .then((response) => {
    return response.text();
  })
  .then((html) => {
    document.body.innerHTML = html     
  });
}
  • 1-调用函数fetch并添加页面路径。
  • 2-然后通过函数.text().
  • 将获取的数据转换为文本
  • 3- 然后 append 页面组件到您的父容器。

       async function getAbout() {


    await fetch('./component/about.html').then(res => res.text()).then(data => {
    page_2.innerHTML = data;

     }).then(() => {
       
         // after fetch write js code here  
     })}

  • 获取,组件不添加<body><HTML>标签<只需使用其他类似<div>或其他标签。

  • 为了更好的性能使用 async-await!.

将 Promise Chaining 与 .then() 结合使用是一种较旧的编码提取和响应的方法。更现代的方法是使用 async functions and 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()

使用这个:

var fetchAndParse = async (url) => { let div = document.createElement("div"); div.innerHTML = await (await fetch(url)).text(); return div }

今天我想知道所有 OpenSource 许可证的长度。我在 https://opensource.org/licenses/alphabetical 上得到了 运行 这样的代码(删除 .slice(0, 3) 以将其映射到所有链接):

var $$ = (x) => ([...document.querySelectorAll(x)])
var fetchAndParse = async (url) => { let div = document.createElement("div"); div.innerHTML = await (await fetch(url)).text(); return div }
var waitTimeout = async (duration) => { return new Promise((accept) => setTimeout(accept, duration)) }
var licenseArray = await Promise.all($$("#main a[href]").slice(0, 3).map(async (anchor, k) => {
  let text = await fetchAndParse(anchor.href).then(div => div.querySelector("#main").textContent.replace(/\s+/g, ' ').trim()).catch(error => { console.error(anchor.href, error); return '' })
  return [anchor.href.replace(/^.*\//, ''), anchor.textContent.length, text.length, anchor.textContent, { href: anchor.href, text }]
}))