-1

Possible Duplicate:
XML parsing using jQuery

Let's say the XML file is this:

<blah>
 <test>This is a test</test>
</blah>

And let's say I have the following HTML:

<div id="example"></div>

How can I extract the contents of test from the XML file and make it the contents of #example in the HTML code with jQuery?

Also, let's say the XML file is hosted on a different domain than the HTML code.

Community
  • 1
  • 1
UserIsCorrupt
  • 4,837
  • 15
  • 38
  • 41

2 Answers2

0

You could do something like:

$.ajax({
  dataType: "jsonp xml",
  url: "http://mydomain.com/xmlfile.xml",
}).done(function(data) { 
  $('#example').append($(data).find('test').text());
});
Ricardo Rodrigues
  • 2,198
  • 2
  • 18
  • 22
0

My suggestion would be to use JSON and jQuery's $.post (or $.ajax) rather than XML if you have the choice. It'll save you some headaches, IMO. Mind you, it's a disputed issue - some basic discussion of the choice is found here.

The basic form I use is as follows:

var namevariable="Suzie", agevariable=43;
var dS=JSON.stringify({"name":namevariable,"age":agevariable});
$.post('destination.php',{data:dS},function (res){
  var o=JSON.parse(res);
  // Return JSON format:  {"unit":"13","subject":"English"}  
  $("#example").html(o.subject);
},"text");  // closing argument of $.post

This sends the name and age fields to destination.php. It then expects destination.php to return a unit and subject variable. The subject variable is then put into your <div id='example'></div>.

There's heaps of help on this site and the net if you choose to use this method.

You can, for example, check the format of your JSON data using JSONLint.

Nick
  • 5,995
  • 12
  • 54
  • 78