我正在使用 JQuery 创建 XML 字符串。我想打开一个新窗口来向用户显示该字符串,以便他将其保存为 XML 文件。
我没有服务器端,我希望这个 Javascript 脚本与 Firefox 和 Internet Explorer 浏览器兼容。
我发现了很多东西,但没有一个真正有效。
uriContent="data:application/xml," + encodeURIComponent(xmlContent);
var newWindow=window.open(uriContent,'_blank','toolbar=0,location=0,directories=0,status=0, scrollbars=1, resizable=1, copyhistory=1, menuBar=1, width=640,height=480, left=50, top=50');
或者对于 IE:
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlContent);
var newWindow = window.open('','_blank','toolbar=0, location=0, directories=0, status=0, scrollbars=1, resizable=1, copyhistory=1, menuBar=1, width=640, height=480, left=50, top=50', true);
newWindow.document.writeln(xmlDoc.documentElement.xml);
newWindow.document.close();
第一个解决方案对于 Firefox 几乎可以正常工作,但不适用于 IE:
第二个源代码打开一个包含 XML 内容的窗口,但 IE 无法将其识别为 XML...因此用户必须自己显示源代码。这不太方便。
有人有解决办法吗?
谢谢!
最佳答案
如果将 XML 视为内容会怎样?
var newWindow = window.open('','_blank','toolbar=0, location=0, directories=0, status=0, scrollbars=1, resizable=1, copyhistory=1, menuBar=1, width=640, height=480, left=50, top=50', true);
var preEl = newWindow.document.createElement("pre");
var codeEl = newWindow.document.createElement("code");
codeEl.appendChild(newWindow.document.createTextNode(xmlContent));
preEl.appendChild(codeEl);
newWindow.document.body.appendChild(preEl);
...那么你可以使用类似Google Code Prettify的东西或SyntaxHighlighter添加您需要的任何突出显示。
关于Javascript - 在浏览器中渲染动态生成的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016998/