0

Okay so I got this Javascript code, and i use it to display some XML in HTML.

   var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

// Append "RSS Title" to #someElement
$( "#someElement" ).append( $title.text() );

// Change the title to "XML Title"
$title.text( "XML Title" );

// Append "XML Title" to #anotherElement
$( "#anotherElement" ).append( $title.text() );

But I would like to use an XML file instead of a string. I tried something like this:

   var xml = $.get("myfile.xml"),
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

// Append "RSS Title" to #someElement
$( "#someElement" ).append( $title.text() );

// Change the title to "XML Title"
$title.text( "XML Title" );

// Append "XML Title" to #anotherElement
$( "#anotherElement" ).append( $title.text() );

(myfile.xml would contain the same text as the string did) Sorry if this is really obvious, im a newbie when it comes to JavaScript :D PS: Just let me know in the comments if i forgot to mention something!

1 Answer 1

1

$.get is asynchronous by default.

Use:

$.get("myfile.xml", function (xml) {
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

  // Append "RSS Title" to #someElement
  $( "#someElement" ).append( $title.text() );

  // Change the title to "XML Title"
  $title.text( "XML Title" );

  // Append "XML Title" to #anotherElement
  $( "#anotherElement" ).append( $title.text() );
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.