dit*_*tto 33 javascript fetch-api
我正在尝试获取文件并返回它的HTML.然而,它并不像我想象的那么简单.
fetch('/path/to/file')
.then(function (response) {
return response.body;
})
.then(function (body) {
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
这将返回一个名为的对象ReadableByteStream.如何使用它来获取HTML文件内容?
如果我将内容更改/path/to/file为JSON字符串,并将上面的内容更改为:
fetch('/path/to/file')
.then(function (response) {
return response.json();
})
.then(function (json) {
console.log(json);
});
Run Code Online (Sandbox Code Playgroud)
...它正确返回JSON.我该如何获取HTML?
Vla*_*vić 44
您可以使用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);
});Run Code Online (Sandbox Code Playgroud)
bro*_*ick 36
您需要使用该.text()方法,而不是.json().这会将字节流转换为纯文本,可以由浏览器将其解析为HTML.
小智 13
使用 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
}
}
Run Code Online (Sandbox Code Playgroud)
关于问题的直接答案(与其他所有答案一样),.text()而不是.json()在响应中使用。
小智 10
您可以使用 返回响应.text(),然后根据需要在文档中呈现页面。
function fetchHtml() {
fetch('./file.html')
.then((response) => {
return response.text();
})
.then((html) => {
document.body.innerHTML = html
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30995 次 |
| 最近记录: |