tags:

views:

29

answers:

2

can somebody help me select the url from this XML document where the ID = 2. via ajax.

<images>
<image id=0>
<url>images/pic.jpg</url>
</image>
<image id=1>
<url>images/pic.jpg</url>
</image>
<image id=2>
<url>images/pic.jpg</url>
</image>
</images>

I am guessing something like this... But currently it is displaying all the entries in the xml. i only want it to load one image, how do i do this please?

$.ajax({
            type: "GET",
            url: "images.xml",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('image').each(function(){
                    var id = $(this).attr('id'); //maybe something here?????
                    var url = $(this).find('url').text();
                    $('.loading').html('<img src='+url+' />');
                });
            }
        });
+1  A: 

It should be:

       success: function(xml) {
            $(xml).find('image').each(function(){
                var id = $(this).attr('id');

                if (id == 2)
                {
                  var url = $(this).find('url').text();
                  $('.loading').html('<img src='+url+' />');
                }
            });
        }

If you just want to find image with id equal to 2, you can simply do this rather than using each:

$(xml).find('image#2 > url').text();
Sarfraz
thanks, quick question if #2 was a variable called i would it be?$(xml).find('image#i > url')?
Adam
@Admin: Yes but it should be like this: `$(xml).find('image#' + i +' > url')`
Sarfraz
+2  A: 

You can do it with an attribute-equals selector, like this:

$.ajax({
    type: "GET",
    url: "images.xml",
    dataType: "xml",
    success: function(xml) {
      var img = $(xml).find('image[id=2]'),
                id = img.attr('id'),
                url = img.find('url').text();
      $('.loading').html('<img src="'+url+'" />');
    }
});

This eliminates code on your side, since jQuery will find the element you want and you're only dealing with that one element.

Nick Craver
And `'image[id=2]'` would be `'image[id=' + somevar + ']'` if you have a variable named `somevar` rather than always id=2
Chad
Thanks guys, I knew there was going to be something simple to add in find() but i could not work out what it was.i just need to start working on my code efficience now..Tar
Adam