javascript - 使用 Ajax 加载 XML 文件 [面向对象]

标签 javascript jquery ajax xml

这是我的 xml 文件的示例,其中包含 <studentenhuizen>重复多次:

<studentenhuis>
  <studentenhuizen>
    <adres>Aalbeeksesteenweg</adres>
    <huisnr>19</huisnr>
    <gemeente>KORTRIJK</gemeente>
    <aantal_kamers>14</aantal_kamers>
  </studentenhuizen>
</studentenhuis>

我的对象

function StudentenKot(adres, huisnr, gemeente, aantalkamers){
    this.adres = adres;
    this.gemeente = gemeente;
    this.huisnr = huisnr;
    this.aantalSlaapkamers = aantalkamers;
};

加载 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>");
        });
    }
});

当添加到<div class="gemeente">时它说“未定义”。 这以前有效,但现在显示 [Object object]

alert($(xml).find("adres")); 

最佳答案

this.adres - I confused it with json haven't I?

是的,你有。这应该说undefined当对其进行警报/字符串化时。

$(xml).find("adres") - it says [Object object] now

是的,什么find返回是一个 jQuery 集合对象,它将被字符串化为 "[object Object]" 。你想要:

  • 不是 <adres>节点(也不是带有它的 jQuery 集合),而是它的文本内容
  • 搜索当前<studentenhuizen>节点,而不是整个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()
     ));
});

关于javascript - 使用 Ajax 加载 XML 文件 [面向对象],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222990/

相关文章:

javascript - REST 中未定义 jQuery Ajax 对象点符号

javascript - for 循环中元素的批量分配

jquery - ASP.NET MVC 4 不支持 jquery datepicker

javascript - 将对象和文件从 ajax 非法调用传递到 Web Api 2 Controller

javascript - 我是 javascript 新手,我正在从 url 获取 JSON 数据,我只能访问 success 函数中的数据,我是否遗漏了什么?

php - 如何使文本中的每个单词都可以点击并将其发送到脚本

javascript - 将 css 应用于弹出窗口中的表格

javascript - Ace Editor - 只读变量

javascript - 使用 D3 在图像上绘制圆圈 - ReactJS

jQuery:从类中获取 ID