S.P. S.P. - 1 year ago 51
jQuery Question

Cannot get xml data with jQuery

I'm trying to get XML data from server, the XML format looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<env:Envelope xmlns:env="httpd://www.w3.org/org/2003/05/spap-envlop" env:encodingStyle="httpd:

And I can see all the XML data from Google chrome console with

$(function() {
$.get("../setup/web.xml", function (data) {

In the Google chrome console message, it shows "#document" and a small arrow sign tells me that's a fold up message, then I click the arrow sign, my XML data showed up. But I still can't figure out why can't I get XML tag's text from my code below:

$(function() {
$.get("../setup/web.xml", function (data) {
$("#ip").text(data.ip) //undefined
$("#domain").text(data.domain) //undefined

Or even this one:

$(function() {
$.get("../setup/web.xml", function (data) {
$(data).find("env:Body").each(function () {
$("#ip").text(ip) //undefined
$("#domain").text(domain) //undefined

Answer Source

The issue is due to the way you're accessing the returned data. You're using dot notation which is the method used for accessing an object. You're returning XML, so you'll need to traverse the nodes to find the values you require. Also note that you'll need to escape the : in the node name otherwise jQuery will interpret this as a psuedo selector. Try this:

// imagine this is the response text from the request
var data = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><env:Envelope xmlns:env="httpd://www.w3.org/org/2003/05/spap-envlop" env:encodingStyle="httpd://www.w3.org/org/2003/05/spap-envlop"><env:Body><ip></ip><domain>Website</domain></env:Body></env:Envelope>';

// this would be inside the callback function of your AJAX request:
var $xml = $(data);
$xml.find('env\\:Body').each(function() {
  var ip = $(this).find('ip').text();
  var domain = $(this).find('domain').text();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ip"></div>
<div id="domain"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download