无法使用XMLHttpRequest对象获取数据

时间:2013-11-20 23:27:07

标签: javascript ajax xml

我正在尝试从与HTML文件位于同一目录的XML文件中获取数据,但似乎没有返回任何数据(我不确定如何在以后呈现数据)。这是脚本(以及我试图解析的XML文件中的示例记录)。谢谢你的帮助!

   function getFromAndDoThis(r, callback, opt="") {

    var okay = true;

    var xhr = new XMLHttpRequest();

    if (xhr) {  
        xhr.addEventListener("readystatechange", function() {callback(opt);}, false);
        xhr.open("GET", r, true);
        xhr.send(null);
    }
    else {
        okay = false;
    }

    return okay;

}

/* callback function */

function displayCurriculum(which) {

    var data = null;
    var chapters, docroot;

    data = extractXMLData(xhr);

    if (data) {

        chapters = data.getElementsByTagName("Chapter");
        docroot = document.getElementsById("contentarea")[0];

        var i = 0;

        /* put each chapter and synopsis (if any) in nodes, and put these nodes in the DOM */       

        for (i=0; i < chapters.length; i++) {

            var chapter = chapters[i];
            var synopsis = chapter.firstChild;

            var div = document.createElement("div");

            var pc = document.createElement("p");
            var ps = document.createElement("p");

            div.setAttribute("id", toString(i));

            pc.innerHTML = chapter.innerHTML;
            ps.innerHTML = synopsis.innerHTML;

            /* nodes are filled. now attach them to the DOM */

            div.appendChild(pc);
            div.appendChild(ps);

            body.appendChild(div);

        } // end for

    } // end if
    else {
        alert("No data.");
    }

} 

XML记录:

<?xml version="1.0"?>
<Curriculum name="algebra">
    <Chapter>
        Numbers
        <Synopsis>
            Real numbers, the number line, arithmetic, factoring, decimals, exponents, radicals, and complex numbers.
        </Synopsis>
    </Chapter>
</Curriculum>

2 个答案:

答案 0 :(得分:2)

您的回调函数正在尝试读取xhr,但该变量超出了范围。您需要将其作为参数传递给回调函数。

答案 1 :(得分:-1)

我没有看到你加载XML。 你可以通过Ajax

来做到这一点
$.ajax({
    type: "GET",
    url: "yourxml.xml",
    dataType: "xml",
    success: function(displayCurriculum){
    }
});