weixin_33712987 2016-05-22 18:16 采纳率: 0%
浏览 17

用ajax加载xml内容

Ok so i have the following html file:

<!DOCTYPE html>
<html>
<style>
  table,
  th,
  td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  th,
  td {
    padding: 5px;
  }
</style>

<body>

  <button type="button" onclick="loadDoc()">Get the names</button>
  <br>
  <br>
  <table id="demo"></table>

  <script>
    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          myFunction(xhttp);
        }
      };
      xhttp.open("GET", "names.xml", true);
      xhttp.send();
    }

    function myFunction(xml) {
      var i;
      var xmlDoc = xml.responseXML;
      var table = "<tr><th>Names</th></tr>";
      var x = xmlDoc.getElementsByTagName("Names");
      for (i = 0; i < x.length; i++) {
        table += "<tr><td>" +
          x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
      }
      document.getElementById("demo").innerHTML = table;
    }
  </script>

</body>

</html>

And the following xml file containing names:

<?xml version="1.0" encoding="UTF-8" ?>
<Names>
  <Name>Alex</Name>
  <Name>Anna</Name>
  <Name>Eva</Name>
  <Name>George</Name>
  <Name>Jason</Name>
  <Name>John</Name>
  <Name>Lisa</Name>
  <Name>Mary</Name>
  <Name>Michael</Name>
  <Name>Nick</Name>
  <Name>Vicky</Name>
</Names>

And what i want is to somehow take the names from the xml file and store them inside an array and then print them.But for some reason only the first name is stored correctly("Alex").I dont understand what i have done wrong.Can somebody help me? I bet there is something wrong with the myFunction(xml) but i cant find/fix it

  • 写回答

2条回答 默认 最新

  • weixin_33714884 2016-05-22 18:57
    关注

    There is only one Names tag so your loop will only execute once.
    I would loop over the Name tags instead.

    function myFunction(xml) {
      var i;
      var xmlDoc = xml.responseXML;
      var table = "<tr><th>Names</th></tr>";
      var x = xmlDoc.getElementsByTagName("Name");
      for (i = 0; i < x.length; i++) {
        table += "<tr><td>" +
          x[i].childNodes[0].nodeValue;
      }
      document.getElementById("demo").innerHTML = table;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 方程如何编到C语言!
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了