我有一个使用 XMLHttpRequest() 在 DOM 中插入内联 svg 的函数,我想知道是否可以使用 fetch() 执行相同的函数。功能是...
el = document.querySelector('#foo')
var request = new XMLHttpRequest()
request.open('GET', 'bar.svg', true)
request.onreadystatechange = function() {
if (this.readyState !== 4) return
if (this.status !== 200) return
el.innerHTML = this.responseText
}
request.send()
// bar.svg is inserted in element with ID 'foo'
那么,是否有可能将此功能现代化为...
fetch('bar.svg').then(...)
最佳答案
你可以。我认为以下应该有效:
fetch('bar.svg')
.then(r => r.text())
.then(text => {
el.innerHTML = text;
})
.catch(console.error.bind(console));
第二个then
用于解决 .text()
,它“获取响应流并将其读取完成”(MDN)(MDN Eng)。
关于javascript - 我可以使用 JavaScript fetch() 在 DOM 中插入内联 svg 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240363/