views:

323

answers:

1

I'm using AJAX to receive an XML response, which I then need to manipulate. By using jQuery's context option, I can select from the XML data, but I am still unable to write to it.

$('blah', xml)

selects xml just fine, but

$('blah', xml).removeClass( 'myClass' )

seems to do nothing to the xml variable! How can I achieve the functionality I'm looking for?

Example:

var data = null;

$(document).ready(function(){
$.ajax({
   type:"GET",
   url:"blah/blah.jsp",
   success:function(msg)
   {
      data = msg;
      init();
   }
});

function init()
{
   $('#myElement', data).removeClass('hidden');//removeAttr('class') also fails
}

Example xml file:

<root>
<div>
<!--lots of content -->
</div>
<div>
<p id = "myElement<->" class = "hidden">
  Test!
</p>
</div>
</root>
+1  A: 

This works for me.

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
    $(function()
    {
    var data = null;
    $.ajax({
        type:"GET",
        url:"sample.xml",
        dataType: 'xml',
        success:function(msg)
        {
           init( $(msg) );
        }
    });

    function init( $xml )
    {
      var $myElement = $xml.find( '#myElement' );
      $myElement.removeAttr( 'class' );
      console.log( $myElement );
    }
    });
    </script>
</head>

<body>

</body>
</html>

And here's sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<div>

</div>
<div>
<p id = "myElement" class = "hidden">
  Test!
</p>
</div>
</root>

so make sure you are requesting with "xml" as the dataType option, and that your JSP page returns the content with the correct Content-Type header (text/xml)

Peter Bailey
*repeatedly clicks up vote, hoping it might shoot to 100.*Content-type on a jsp response header. What a subtle bug.
Stefan Kendall
Also be aware of the possibility of needing to use msg.d instead of just msg. http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
Maslow