>我正在尝试加载由php文件生成的svg图像。 如果我使用标准的 svg 表示法,它适用于支持 svg 的浏览器,这并不是什么新鲜事:
<svg><rect x="20" y="40" width="100" height="200" /></svg>
另一方面,如果我尝试相同的方法,但这次使用 svg web 文档中描述的符号 http://svgweb.googlecode.com/svn/trunk/docs/UserManual.html(我在任何其他 javascript 文件之前导入 svg web 文件),但没有任何反应:
<script type="image/svg+xml"><svg><rect x="20" y="40" width="100" height="200" /></svg></script>
我制作了一个脚本来执行 xmlhttprequest 响应文本中的所有 javascript,使用 eval。所有"正常"的JavaScript都可以工作,但这不能。有人知道我做错了什么吗?
下面是 XHR 函数:
function loadXMLDoc(file, div){var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", file, true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var myresponse = xmlhttp.responseText;
var mydiv = document.getElementById(div);
mydiv.innerHTML=myresponse;
}
if(xmlhttp.status==404){
document.getElementById(div).innerHTML="<h1>File not found</h1>";
}
}
xmlhttp.send();
}
下面是使用 xhr 加载的 php 文件之一的示例(我不包括实际上会生成 svg 的 php 类):
echo '<script type="image/svg+xml"><svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" version="1.1" baseProfile="full">
<rect x="0" y="0" width="60" height="60" style="stroke: green;"/>
<rect x="25" y="25" id="myRect" rx="0.6" ry="0.6" width="150" height="150" fill="green" stroke="yellow" stroke-width="8"/>
</svg></script>';
?>
对于 php 文件,如果删除标签,它将通过使用对 svg 的本机支持来工作,但 svg web 将不起作用。
提前谢谢。
我没有使用过SVGWeb,但这个答案完全基于您为文档提供的链接。
首先解释为什么你的方法不起作用。在没有阅读代码的情况下,我猜测 SVGWeb 的工作方式是解析 HTML 页面以获取时髦的 <script type="image/svg+xml">
标签,并在页面加载时需要将它们转换为 flash。
显然,这意味着添加到页面的任何内容都不会被解析,因为页面加载事件只触发一次。这就是为什么你的方法不起作用。
幸运的是,SVGWeb确实提供了一个API来在运行时在IE中渲染SVG对象。这是一种称为的方法:svgweb.appendChild()
(搜索文档)。不幸的是,svgweb.appendChild
方法不接受字符串作为参数,但需要一个正确解析的 svg 对象。幸运的是,文档解释了如何在运行时获取该对象。但是你不能用XMLHttpRequest
来做.
以下是文档说明您可以做到这一点的方式(阅读Dynamically Creating an SVG OBJECT
部分):
var obj = document.createElement('object', true);
obj.setAttribute('type', 'image/svg+xml');
obj.setAttribute('data', 'rectangles.svg'); // <-------- this is where you
obj.setAttribute('width', '500'); // load the file from
obj.setAttribute('height', '500'); // your server
// And this is how you add the SVG object to your document:
obj.addEventListener('load', function() {
svgweb.appendChild(obj, document.body);
}, false);
请注意,它不必是 document.body
.它可以是div或表格等。