gpt4 book ai didi

javascript - 使用 fetch() 返回 HTML

转载 作者:行者123 更新时间:2023-12-02 19:22:06 24 4
gpt4 key购买 nike

我正在尝试获取文件并返回其 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);
});

关于javascript - 使用 fetch() 返回 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com