使用ajax通过xml循环

时间:2014-06-12 13:11:50

标签: jquery ajax xml loops each

我尝试使用每个循环尝试获得多个带名,但我得到的只是循环中的最终名称。谁能告诉我我做错了什么。

XML结构:

<resultsPage>
  <results>
    <event type="concert">
      <performance displayName="bandname1"></performance>
      <performance displayName="bandname2"></performance>
      <performance displayName="bandname3"></performance>
    </event>
  </results>
</resultsPage>

AJAX:

$.ajax({
    url: 'xml/timeline.xml',
    dataType: 'xml',
    success: function(data){
        $(data).find('resultsPage results event').each(function(){
            var type = $(this).attr('type');
            var band = $(this).find('performance artist').each(function(){
                name = $(this).attr('displayName');
            })

            $('.timeline ul').append(
                '<li>A '+type+' played by '+name+'</li>'
            );

        });
    },
    error: function(){
        $('.timeline').text('Failed to get feed');
    }
});

1 个答案:

答案 0 :(得分:2)

您在每次迭代中覆盖name变量。改为:

$(data).find('resultsPage results event').each(function(){
    var type = $(this).attr('type');
    var band = $(this).find('performance artist');
    var length = $(band).length;
    $(band).each(function(index, element){
        name += $(this).attr('displayName');
        if (index < length-1) {
           name += ", ";
        }
    });

    $('.timeline ul').append(
        '<li>A '+type+' played by '+name+'</li>'
    );

});