我可以使用JavaScript fetch()在DOM中插入内嵌svg吗? [英] Can I use JavaScript fetch() to insert an inline svg in the DOM?

查看:84
本文介绍了我可以使用JavaScript fetch()在DOM中插入内嵌svg吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用XMLHttpRequest()在DOM中插入内嵌svg的函数,我想知道是否可以使用fetch()做同样的功能.功能是...

I have a function that inserts an inline svg in the DOM using XMLHttpRequest() and I'm wondering if I can do the same function using fetch(). The function is...

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'

因此,是否有可能将此功能现代化为...

So, is it possible to modernize this function into something like...

fetch('bar.svg').then(...)

推荐答案

可以.我认为以下方法应该有效:

You can. I think the following should work:

fetch('bar.svg')
    .then(r => r.text())
    .then(text => {
        el.innerHTML = text;
    })
    .catch(console.error.bind(console));

第二个获取是用于解析.text()的操作,该操作获取响应流并将其读取到完成"( MDN ).

The second fetch is for resolving the .text(), which "takes a Response stream and reads it to completion" (MDN).

这篇关于我可以使用JavaScript fetch()在DOM中插入内嵌svg吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆