Javascript 使用 fetch() 返回 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36631762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:19:53  来源:igfitidea点击:

Returning HTML With fetch()

javascriptfetch-api

提问by ditto

I'm trying to fetch a file and return it's HTML. However it's not as simple as I'd have imagined.

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

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

This returns an object called ReadableByteStream. How do I use this to grab the HTML file content?

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

If I change the contents of /path/to/fileto be a JSON string, and change the above to:

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

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

... it returns the JSON correctly. How do I do fetch HTML?

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

回答by Vladimir Jovanovi?

You can download the html with fetch and then parse it with DomParser API.

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

回答by bronzehedwick

You need to use the .text()method, instead of .json(). This converts the byte stream into plain text, which can be parsed by the browser as HTML.

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

回答by mahmoud miz

you can return the response with .text(), and then render the page in the doc as you want.

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

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

回答by Tr?n Nguyên Khuy?n

It should be:

它应该是:

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