问题描述:

I have a sample XML file.

<?xml version="1.0"?>

<people>

<person>

<name> Joe </name>

<age> 45 </age>

</person>

<person>

<name> Dan </name>

<age> 25 </age>

</person>

</people>

The idea is to pull the name of each person using jQuery.

I am finding difficulties in using $.ajax( { } ); call to pull the data.

How to clean up the following sample code?

$.ajax( {

url:"people.xml",

dataType: "json",

success:function(element,value)

{

$(element).find(value).each(function()

{

alert($(this).find("name").text()

});

});

}

}

);

网友答案:

First of all since you are retrieving XML you must set dataType to XML.

Then some parentheses fixes to your code and it should work

$.ajax({
    url: "people.xml",
    dataType: "xml",
    success: function (data) {
        $(data).find('name').each(function () { // get the names from data
            alert($(this).text());
        });
    }
});

FIDDLE

网友答案:

name of each person can be pulled like this

$.ajax({
    url: "people.xml",
    success: function(data) {
        var names = $(data).find('name');
        $.each(names, function(i, name) {
            alert($(name).text());
        });
    }
});
网友答案:

Your DataType is wrong.You must change it to "xml".

You can change your code something like:

$.ajax(
       {
         url:"people.xml ",  //please specify the correct path
         dataType: "xml",    //Here the data type is XML
         success:function(data)
          {
           // if the parsing of the URL
           // is successful this anonymous call get executed
            $(data).find("person")
                   .each(
                         function() 
                         {
                           alert($(this).find("name").text());
                         }
                        );
          });

       }); 
相关阅读:
Top