无法从xml文件中获取数据

时间:2015-03-26 07:44:38

标签: javascript ajax xml

编写了以下ajax行来从xml文件中获取一些数据。但它没有这样做。没有抛出错误。但是浏览器窗口中没有显示任何数据。我有我的xampp runnign但是可以&# 39;弄清楚为什么会发生这种情况。任何人都可以帮我解决这个问题吗?

<body>
<p id='suggestion'></p>
<script>
   function initialize(){

      var suggest=document.getElementById('suggestion');
      var xmlhttp,txt,elem,l;
      if(window.XMLHttpRequest){
          xmlhttp=new XMLHttpRequest();
      }else if(window.ActiveXObject){
          xmlhttp=new ActiveXObject();
      }
      if(xmlhttp){

      if(xmlhttp.readyState==4 && xmlhttp.status==200){

      xmlhttp.onreadystatechange=function(){
           elem=xmlhttp.responseXML;
           l=elem.getElementsByTagName('cd');
           for(i=0;i<l.length;i++){
               txt+=l[i].getELementsByTagName('title')[0].firstChild.data;
           }

        }   
      xmlhttp.open('GET','new.xml',true);
      xmlhttp.send(null);

      suggest.innerHTML=txt;
      }
     }
   }
   window.onload=initialize;
</script>

xml文件:

<? xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<catalog>
<cd>
   <title>Empire Burlesque</title>
   <artist>Bob Dylan</artist>
</cd>
<cd>
   <title>We are all we need</title>
   <artist>above and beyond</artist>
</cd>
</catalog>

1 个答案:

答案 0 :(得分:1)

xmlhttp.onreadystatechange在条件包装器中分配 - 除非xmlhttp已经处于readyState 4并且状态为200(并且不太可能),否则不会分配它。

尝试交换行

if(xmlhttp.readyState==4 && xmlhttp.status==200){

xmlhttp.onreadystatechange=function(){
相关问题