Read unknown array size in Ajax from XML

How can I read and sign XML data (array of different sizes) using jQuery?

AJAX read node string from XML and store in javascript array, XML array size is not constant.

My code is:

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "sites.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('msg').each(function() {
                var title = $(this).find('title').text();
                i = 0;
                tic = new Array();
                $(this).find('desc').each(function() {
                    tic.push($(this).find('line').text());
                    alert(tic[i]);
                    i++;
                });
            });
        }
    });
});

and XML file (demo)

<msgs>
    <msg>
        <title>ABC</title>
        <desc>
            <line>test 1</line>
            <line>test 2</line>
            <line>test 2</line>
        </desc>
        <time>5</time>
    </msg>
</msgs>

Can someone help me please

+3
source share
1 answer

To read all elements linein an array change

tic.push($(this).find('line').text());

to

$(this).find('line').each(function() {
    tic.push($(this).text());
})

This will process each element lineand add it to your array, and then place the array initialization at the top var tic = [];... so the full success function will look like this:

var tic = [];
$(xml).find('msg').each(function() {
    var title = $(this).find('title').text();
    $(this).find('line').each(function() {
        tic.push($(this).text());
    });
});​

Working example here

0
source

All Articles