JQuery Find an XML element based on the value of one of its children

I am working on a simple XML notebook to learn JQuery, and I can’t figure out how to do it: When a user types a contact’s name in a text box, I want to find the whole record of that person. XML looks like this:

<phonebook>
<person>
    <number> 555-5555</number>
    <first_name>Evelyn</first_name>
    <last_name>Remington</last_name>
    <address>Edge of the Abyss</address>
    <image>path/to/image</image>
</person>
<person>
    <number>+34 1 6444 333 2223230</number>
    <first_name>Max</first_name>
    <last_name>Muscle</last_name>
    <address>Mining Belt</address>
    <image>path/to/image</image>
</person>
</phonebook>

and the best I could do with jQuery is something like this:

var myXML;
function searchXML(){
  $.ajax({
     type:"GET",
     url: "phonebook.xml",
     dataType: "xml",
     success: function(xml){myXML = $("xml").find("#firstNameBox").val())}
  });
 }

What I want to do is to return the entire element <person>so that I can iterate and display all the information of this person. Any help would be appreciated.

+3
source share
1 answer

, , <person> , Evelyn ;

var myXML; 

function searchXML(){
  $.ajax({
     type:"GET",
     url: "phonebook.xml",
     dataType: "xml",
     success: function(xml){
              // Filter Evelyn out of the bunch
            myXML = $(xml).find("person").filter(function() {
                return $(this).find('first_name').text() == "Evelyn";
            });

              // Store a string with Evelyn info in the display variable
            var display = myXML.children().map(function() {
                return this.tagName + '=' + $(this).text();
            }).get().join(' ');

              // alert the result
            alert(display);
        }
  });
}
searchXML();

EDIT:

, "" <person>, , , . , , AJAX, <person> myXML undefined.

, success, , success.

, , .

, , . , . , :

$(xml).find("person").each(function() {
    // do your processing...
});
+6

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


All Articles