Thursday, January 1, 2009

[jQuery] Re: parsing xml

Try using a base element:
<items>
<item>
sample one
</item>
<item>
sample two
</item>
</items>

jQuery needs a context for find() to work.

On Jan 1, 6:22 pm, jhm <jmay...@gmail.com> wrote:
> I'm new to jquery and I'm trying to do a simple xml parse.
>
> When I use the .each() to get the tags, if there is more than one tag
> in the file, nothing more in the script gets processed. In the code
> below, you'll see two alerts. If I comment out the .each() line I get
> both alerts. If I leave it in, only the first appears and I never see
> any alerts from the .each() statement.
>
> Can anyone tell me what's wrong? Here's the code:
>
> -------------------------------------------------------------------------------------
> <!doctype html public"-//w3c//dtd xhtml 1.0 Transitional//en"
> "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
> <head>
>   <script src="./scripts/jquery.js" type="text/javascript"></script>
>   <script type="text/javascript">
>   $(document).ready(function() {
>     $('.button').click(function() {
>       $.get('data.xml', function(data) {
>
>         $('#container').empty();
>         alert('one');
>
>         var html = $(data);
>         $('#container').append(html);
>
>         $(data).find('item').each(function(i) {
>           alert(i);
>         });
>
>         alert('two');
>       }, 'xml');
>     });
>   });
>   </script>
> </head>
>
> <body>
>   <div class="button">Load</div>
>   <div id="container">
>     <p>some placeholder text</p>
>   </div>
> </body>
> -------------------------------------------------------------------------------------
>
> Here's the contents of data.xml:
>
> -------------------------------------------------------------------------------------
> <item>
>         sample one
> </item>
> <item>
>         sample two
> </item>
> -------------------------------------------------------------------------------------
>
> Remove the second item and it works with the .each() left in.
>
> Thanks!

No comments: