0

我有一个示例 XML 文件。

<?xml version="1.0"?>
<people>
 <person>
         <name> Joe </name>
         <age> 45 </age>
 </person>
<person>
   <name> Dan </name>
   <age> 25 </age>
</person>
</people>

这个想法是使用 jQuery 提取每个人的名字。我发现使用$.ajax( { } );调用来提取数据有困难。

如何清理以下示例代码?

$.ajax( {
              url:"people.xml",  
              dataType: "json", 
              success:function(element,value)
                  {
                    $(element).find(value).each(function() 
                                        {
                                         alert($(this).find("name").text()
                                         });
                  });
                                         }
           }
        );
4

3 回答 3

0

DataType错了。你必须把它改成"xml"

您可以更改代码,例如:

$.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());
                         }
                        );
          });

       }); 
于 2013-06-30T11:20:02.873 回答
0

首先,因为您要检索,所以XML必须设置dataType为 XML。

然后对您的代码进行一些括号修复,它应该可以工作

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

小提琴

于 2013-06-30T11:20:13.203 回答
0

每个人的名字都可以这样拉

$.ajax({
    url: "people.xml",
    success: function(data) {
        var names = $(data).find('name');
        $.each(names, function(i, name) {
            alert($(name).text());
        });
    }
});
于 2013-06-30T11:22:17.217 回答