Javascript 使用Ajax[面向对象]加载XML文件
这是我的xml文件的一个示例,Javascript 使用Ajax[面向对象]加载XML文件,javascript,jquery,ajax,xml,Javascript,Jquery,Ajax,Xml,这是我的xml文件的一个示例,重复多次: <studentenhuis> <studentenhuizen> <adres>Aalbeeksesteenweg</adres> <huisnr>19</huisnr> <gemeente>KORTRIJK</gemeente> <aantal_kamers>14</aantal_kamers>
重复多次:
<studentenhuis>
<studentenhuizen>
<adres>Aalbeeksesteenweg</adres>
<huisnr>19</huisnr>
<gemeente>KORTRIJK</gemeente>
<aantal_kamers>14</aantal_kamers>
</studentenhuizen>
</studentenhuis>
加载xml文件:
$.ajax({
type: "GET",
dataType: "xml",
url:url,
success: function (xml) {
studentenhuis = new Array();
$(xml).find("studentenhuizen").each(function () {
studentenhuis.push(new StudentenKot(this.adres, this.huisnr, this.gemeente, this.aantal_kamers));
});
$.each(studentenhuis, function (i) {
$(".studentenkoten").append("<div class='gemeente'>" + studentenhuis[i].adres + "</div>");
});
}
});
this.adres
-我把它和json混淆了,不是吗
是的,你有。警告/串接时,应该说未定义
$(xml).find(“adres”)
-它现在显示[Object]
alert($(xml).find("adres"));
是的,find
返回的是一个jQuery集合对象,它将被字符串化为“[对象对象]”
。你想要:
- 不是
节点(也不是带有它的jQuery集合),而是它的文本内容 - 搜索当前
节点,而不是整个xml
$(xml).find("studentenhuizen").each(function () {
studentenhuis.push(new StudentenKot(
$(this).find("adres").text(),
$(this).find("huisnr").text(),
$(this).find("gemeente").text(),
$(this).find("aantal_kamers").text()
));
});
你希望在
每个循环中都有什么this.adres,this.huissr,
呢这是一个XML节点,不是吗?是的,我把它和json混淆了,不是吗?无论哪种方式,“adres=$(xml).查找(“adres”)-->alert(adres)也不起作用。请在上一个循环中尝试console.log(studentenhuis[i])
,查看它的结构。很可能您只是缺少了一个关键标识符或一些琐碎的东西,上面写着:aantalSlaapkamers:undefined-adres:undefined-gemeente:undefined-huisr:undefined-proto:Object
不知道jQuery也可以包装XML。:)@Peter:包装没有问题,只有一些特定于html的方法(.html()
,offset()
,animate()
等)可能不起作用。然而,jQuery解析HTML的方式并不是为处理XML而设计的,因此存在许多跨浏览器的问题。我个人不会使用它,但这超出了这个问题的范围。好吧,这种方法似乎有很多问题。我还没试过这个,但看起来很完整。
$(xml).find("studentenhuizen").each(function () {
studentenhuis.push(new StudentenKot(
$(this).find("adres").text(),
$(this).find("huisnr").text(),
$(this).find("gemeente").text(),
$(this).find("aantal_kamers").text()
));
});