2

JS

function loadXml() {

    $.ajax({
        type: 'get',
        url: 'test.xml',
        dataType: 'xml',
        success: function(output) {
            $(output).find('name').each(function() {

    $('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>');

            });
        }
    });

}

HTML

<a href="javascript:void(0)" onClick="loadXml()">Click Me</a>

<table border="1">
    <thead>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Occupation</th>
        <th>Fav Show</th>
    </tr>
    </thead>
    <tbody>
        //
    </tbody>
</table>

XML

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

<people>
    <person>
        <name>Sam Uber</name>
        <age>22</age>
        <occupation>Web Developer</occupation>
        <favshow>Batman</favshow>
    </person>
    <person>
        <name>Jenna Taylor</name>
        <age>18</age>
        <occupation>Model</occupation>
        <favshow>Family Guy</favshow>
    </person>
</people>

The problem is when I click the link it shows the first name "Sam Uber" and that's it. Instead of showing both names from the XML inside the table body. I don't know why this is since that code is within the each() function.

Even stranger is the fact that it works when I alert the names:

alert($(this).text());

instead of

$('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>');

So I guess the problem is there...

1 Answer 1

2

The line $('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>'); is replacing all of the html inside of tbody with the content given to the function.

You should append() the content instead of filling it.

$('table > tbody').append('<tr><td>'+$(this).text()+'</td></tr>');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.