deinonychusaur deinonychusaur - 2 months ago 6
Javascript Question

Create SVG dynamically from from request data

I've tried googling, but information on svg in html is very confusing. I have a quite complex, or at least for me, scenario:

Using jQuery I wan't to create an svg object dynamically inside a div (

id="manual-regridding-image"
) based on response data from a GET-request. The svg will contain both image-data and other svg-elements. If the GET-request fails then the entire contents of the div should be set to the message within the fail-function. Finally decision about showing the contents to the user needs to be made after the image as been fully downloaded/loaded.

What I've gotten so far is:

function load_grid_svg() {

show_gridimage = true;
$.get(
"/api/results/gridding/svg",
function (data) {
svg = document.importNode(data, true);
$("#manual-regridding-image").html(svg);
}
).fail(function() {
$("#manual-regridding-image").html("<em>Could not find the grid image! Maybe gridding failed last time?</em>");
}).always(function() {
if (show_gridimage) {
$("#manual-regridding-image").show();
} else {
$("#manual-regridding-image").hide();
}
});
}


But the importing of the data doesn't work. It feels like this question should have been asked before, but I can't find anything applicably.

Edit



This produces a
NotSupportedError: Operation is not supported
on the
importNode
line if I understand the traceback correctly.

Edit 2



As indicated by @Tomalak in the comments, the response is an
XMLDocument
and to get it to correctly display the callback in the
$.get
should be:

function (data) {
$("#manual-regridding-image").append(data.documentElement);
}

Answer

As indicated by @Tomalak in the comments, the response is an XMLDocument and not only the <svg>...</svg> string, so to get it to correctly display the callback in the $.get should be:

function (data) {
    $("#manual-regridding-image").append(data.documentElement);
}

To ensure the div only shows the most recent content a $(#manual-regridding-image").empty() needs to be performed before the $.get-call.

Comments