【问题标题】:Looping through xml with ajax使用ajax循环遍历xml
【发布时间】:2014-08-02 19:59:05
【问题描述】:

我正在尝试使用 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');
    }
});

【问题讨论】:

    标签: jquery ajax xml loops each


    【解决方案1】:

    您将在每次迭代中覆盖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>'
        );
    
    });
    

    【讨论】:

    • 那么你会得到这样的结果:bandname1 演奏的音乐会,bandname2 演奏的音乐会。但我想要类似:bandname1、bandname 2、bandname3 演奏的音乐会
    • 我已经更新了答案。注意 += 运算符和连接的 ", "。
    • 我的回答对你有帮助吗?
    猜你喜欢
    • 2021-11-12
    • 2019-07-07
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    相关资源
    最近更新 更多