nadieh
nadieh

Reputation: 685

How to use XML data embedded in HTML in javascript (ajax)?

I am pretty new to HTML and such and I am trying to create a HTML page that is completely 'self-contained' so all the CSS, data and JavaScript that it needs will be embedded in the HTML (I know this will create a very ugly HTML file, but I do not mind) I need to do this because I need to be able to send the HTML file to colleagues so they can open it without having to run a local server and without anything being uploaded on an online server.

For now, I've managed to add all the CSS and Javascript, but the Javascript uses ajax to load an external XML file with the data. I cannot seem to get this to work when I embed the XML into the HTML and try to load it through ajax

I've embedded the XML data inside the HTML like so:

<script id="graphFile" type="text/xmldata"> 
   <gexf>
      <graph defaultedgetype="directed" mode="static">
        <attributes class="node" mode="static">
          <attribute id="v_name" title="name" type="string"></attribute>
          <attribute id="indegree" title="In-Degree" type="integer">
            <default>0</default>
          </attribute>
      ...more data...
     </graph>
   </gexf>
</script>

In the javascript the original XML file was parsed like so (which I have taken from the example I am basing my own HTML on):

function loadGraph() {

    $.ajax({
        url: "graphFile.xml",
        dataType: "xml",
        success: function(data) {
           ...calculate stuff...
        }
   });
}

However, I have no idea how I can parse the data from the XML embedded in the HTML so the function(data) will still work

Upvotes: 1

Views: 1350

Answers (1)

Mark
Mark

Reputation: 3123

From XML parsing of a variable string in JavaScript

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

OR you can step away from XML and into JSON, which would be my strong personal recommendation.

Upvotes: 1

Related Questions