. Every JavaScript Function Repeating Twice in XML

I am trying to iterate through xml using jquery and post it to html. For some reason, every function in the author adds duplicates. For example, I will get James McGovernpar BilnerKurt BotnerKurt Kegle James Lynn Valianathan Nagaryan, James McGovern Pierre Botner Kurt BotnerKurt Kegle James Lynn Valianathan Nagaryan. I was wondering how can I fix this? Thanks!

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>

$(document).ready(function() {
$.ajax({

     url: "books.xml",
     dataType: "xml",
     success: function(data) {

        $(data).find('book').each(function(){
        var category = $(this).attr('category');
        var title = $(this).find('title').text();
        var year = $(this).find('year').text();
        var price = $(this).find('price').text();
        var author = $(this).find('author').text();

        $(this).find('author').each(function(){
            author += $(this).text();
            author += ',';
        });

        var r = '<tr>';
        r += '<td>' + title + '</td>';
        r += '<td>' + author + '</td>';
        r += '<td>' + year + '</td>';
        r += '<td>' + price + '</td>';
        r += '<td>' + category + '</td>';

        $('table').append(r);
        });

     },
     error: function() { alert("error loading!");  }
 });

});
+4
source share
2 answers

First you set auther to $(this).find('author').text(), and THEN adds the lines in each. This makes the list repeat.

, var author = ''.

+2

var author = $(this).find('author').text();

var author ='';

- ... .

author, :

var author =[];
$(this).find('author').each(function(){
    author.push( $(this).text());
});    
author = author.join(', ');

// or

var author = $(this).find('author').map(function(){
      return $(this).text();
}).get().join(', ');
+2

Source: https://habr.com/ru/post/1608732/


All Articles