将外部SVG文件加载到变量中并附加到html

将外部SVG文件加载到变量中并附加到html

问题描述:

我正在尝试用此SVG的内容替换IMG标签中嵌入的SVG图像,并将其内联输出.换句话说,将给定IMG SRC属性的SVG文件的内容加载到变量中,并将其作为内联SVG注入HTML中,如下所示:

I'm trying to replace an SVG image embedded in IMG tag with the content of this SVG and output it inline. In other words lo load the contents of SVG file of given IMG SRC attribute into a variable and inject it as inline SVG into HTML, like this:

...

else if (type && type === 'img-simple') {
    if (format === 'svg' ) {
         $.get(src, function(data) {
         var svg = $(data);
         $bg.append(svg);
    });

}其他{

...

其中var类型是图像类,格式是图像类型:jpg,sag等.

Where var type is image class and format is the image type: jpg, sag etc.

这给了我以下错误:

[Error] Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. (img01.svg, line 0)
[Error] XMLHttpRequest cannot load file:///Users/img01.svg. Origin null is not allowed by Access-Control-Allow-Origin. (index.html, line 0)

显然是get函数的问题吗?

Apparently it's the get function problem?

预先感谢

您不能使用file://协议通过ajax加载数据.您需要使用http://

You cannot load data via ajax using the file:// protocol. You need to use http://

例如,将svg文件移动到与javascript文件相同的文件夹,然后执行以下操作:

For example, move the svg file to the same folder as your javascript file and then do:

$.get('img01.svg', function(data) {
    $bg.append(data);
});