我能否使用JavaScript的fetch()方法将内联svg插入到DOM中?

15

我有一个函数,使用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(...)
2个回答

36
您可以。我认为以下内容应该可行:
fetch('bar.svg')
    .then(r => r.text())
    .then(text => {
        el.innerHTML = text;
    })
    .catch(console.error.bind(console));

第二个 then 是用于解析 .text() 的,它“读取响应流以完成”(MDN)(MDN Eng)。


我得到了一个eslint错误(需要// eslint-disable-next-line no-unsanitized/property)与类似的代码...这似乎有些过度,但是真的吗? - Max Waterman
我们能否在不进行网络调用的情况下插入内联SVG?有什么办法吗? - Sabari Krishnan M

-3

是的,fetch返回一个Promise。因此,您可以使用then()和catch(error)来捕获错误。但要注意浏览器兼容性


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接