从XML获取元素的问题

时间:2015-01-10 09:16:29

标签: javascript ajax xml

我正在尝试从我的XML文件中检索一些数据,并且我想将其插入到无序列表中。这就是我的Ajax代码的样子:

var request;
//For backward compatibility
if(window.XMLHttpRequest){
    request = new XMLHttpRequest();
}else{
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','data.xml');
request.onreadystatechange = function(){
    // if((request.readyState === 4) && (request.Status===200)){
        console.log(request.responseXML);
        var items = request.responseXML.getElementByTagName('name');
        alert('hello');
        var ouptput = '<ul>';
        for (var i = 0; i >= items.length; i++) {
            output += '<li>' + items[i].firstChild.nodeValue + '</li>';
        }
        output += '</ul>';
        document.getElementById('update').innerHTML = output;
    //} 
}
request.send();

这段代码没有读取我的XML文件,它给我一个错误说'Response XML is null(Type error)'我试图在服务器(localhost)中使用它,但它也没有用。

有人可以告诉我如何解决这个问题吗?谢谢。

1 个答案:

答案 0 :(得分:0)

我用jQuery来解决这个问题......这就是我这样做的方式.....

<script>
    $(document).ready(function(){
      $(".update").append("<ul></ul>");
      $.ajax({
        type: "GET",
        url: "data.xml",
        dataType: "xml",
        success: function(xml){
        $(xml).find('book').each(function(){
          var sTitle = $(this).find('title').text();
          var sprice = $(this).find('price').text();
          $("<li></li>").html(sTitle + ", " + sprice).appendTo(".update ul");
        });
      },
      error: function() {
        alert("An error occurred while processing XML file.");
      }
      });
    });

</script>