XML : Loop through XML children from AJAX call using jQuery?

I need help with Ajax and jQuery.

I have received this XML data from Ajax call:

  <data>  <book title="Book1" bookID="1">  <AuthorsNum>3</AuthorsNum>  <author>      <authorId>1</authorId>      <fName> Mark </fName>      <mName>null</mName>      <lName>White</lName>      <education>PHD</education>      <role>Writer</role>       </author>  <author>      <authorId>2</authorId>      <fName>Jhon</fName>      <mName>null</mName>      <lName>Brown</lName>      <education>PHD</education>      <role>Writer</role>       </author>  </book>  <book title="Book2" bookID="2">  <AuthorsNum>4</AuthorsNum>  <author>      <authorId>1</authorId>      <fName> Mark </fName>      <mName>null</mName>      <lName>White</lName>      <education>PHD</education>      <role>Writer</role>       </author>  </book>    

I need to create a drop down (select) menu with book names and ids. Then, when each book is selected I need to display authors name and education. For now, I get the drop down list, but I can not figure out how I get the selected book and loop through all the authors for this book to display them.

Here is what I have done:

  printAuthors = function(){      $.ajax({          type: "GET",          async: true,          cache: false,          url: url,          data: {path: "/mypath" },          dataType: "xml",          success: function(data, status){                var myContent = "";              if( $(data).find("error").length!=0){                }                else{                  var selectElement = $("<select id='bookMenu' name='bookMenu' />");                  var content="";                  $( "book", data).each( function() {                      $("<option />", {value: $(this).attr('bookID') , text: $(this).attr('title') }).appendTo(selectElement);                        var selectedOption = this.value;                      $( "author", $(data).find('book[bookID="' + selectedOption + '"]').children()).each( function() {                          // get the name and education and append them to a #myDiv                      });                  });                    $( "#myDiv").html( selectElement ) ;                  }          }        });  }    

Can anyone help? Is there a better approach to implement the menu and results?

No comments:

Post a Comment