使用fetch()返回HTML

Returning HTML With fetch()

本文关键字:返回 HTML fetch 使用      更新时间:2023-09-26

我正在尝试获取一个文件并返回其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?

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

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

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

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

将Promise Chaining与.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);  
});
  • 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>标记<只需使用其他类似CCD_ 16或其他标签。

  • 为了获得更好的性能请使用异步等待!。

使用此:

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

今天我想知道所有OpenSource许可证的长度。我最终在https://opensource.org/licenses/上运行了这样一个代码(删除.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($$(".license-table--title a[href]").slice(0, 3).map(async (anchor, k) => {
  let text = await fetchAndParse(anchor.href).then(div => div.querySelector("#LicenseText, .entry-content").textContent.replace(/'s+/g, ' ').trim()).catch(error => { console.error(anchor.href, error); return '' })
  return [anchor.href.replace(/^.*'/([^/]+)'/?/, '$1'), anchor.textContent.length, text.length, anchor.textContent, { href: anchor.href, text }]
}))