Reputation: 1346
I have a page successfully asking for and parsing some raw SVG from a JSON object. The problem is taking that SVG and putting it into a page. I have:
function addSVGToPage(SVGToAdd) {
var entry, decodedEntry;
makeAJAXCall(SVGToAdd, function (returnedJSON) {
var svgElement;
entry = decodeURIComponent(escape(atob(returnedJSON.data.content.replace(/\s/g, ''))));
decodedEntry = entry.split('\n').slice(2).join('\n'); //remove the first two elements in the file that prevent them from being added as an actual file.
$(insertArea).append(decodedEntry); //insertArea is a <div>
});
}
But it does not seem to putting anything on the page.
What is the best way to go about putting the returned SVG (as a string) on to the page?
Edit: Solution!
The solution is that (due to security or namespce, IDK) you need to parse the raw string as a XML then import it into the DOM. As below
function addSVGToPage(SVGToAdd) {
var entry, decodedEntry, xmlDoc, importedNode;
makeAJAXCall(SVGToAdd, function (returnedJSON) {
var svgElement;
entry = decodeURIComponent(escape(atob(returnedJSON.data.content.replace(/\s/g, ''))));
decodedEntry = entry.split('\n').slice(2).join('\n'); //remove the first two elements in the file that prevent them from being added as an actual file.
xmlDoc = $.parseXML(decodedEntry); // turn the string into an xml fragment
importedNode = document.importNode(xmlDoc.documentElement, true);
document.body.appendChild(importedNode);
});
}
Did not end up using the d3 method, although it was a good one, because the data coming back was JSON containing a base64 encoded string of the SVG (plus some extra declaration stuff) and jQuery capable of handling that without adding in an extra library.
Edit 2: For those interested: http://dougmiller.github.com/SVG-Shapes is the link to where it is set up.
Upvotes: 1
Views: 1804