每个有数组的JavaScript

时间:2017-07-24 08:31:13

标签: javascript arrays xml for-loop foreach

我正在编写一个Javascript应用程序,它从xml文件中获取一些文本并将其显示在html表中。这是我为此任务所拥有的代码:

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    //set servername
    var servername = xmlDoc.getElementsByTagName("servername");
    document.getElementById("server1").innerHTML =
    servername[0].childNodes[0].nodeValue;
    document.getElementById("server2").innerHTML =
    servername[1].childNodes[0].nodeValue;
}

如何更改此函数以在xml文件中执行可变数量的服务器名?

非常感谢你的帮助!

XML文件:

<dashboard>
<server service="PRODUCTION">
    <servername>Testserver1</servername>
    <iis>OK</iis>
    <fim>OK</fim>
    <sql>OK</sql>
    <date>18.07.2017 11:50</date>
</server>
<server service="TEST">
    <servername>Testserver2</servername>
    <iis>OK</iis>
    <fim>OK</fim>
    <sql>OK</sql>
    <date>18.07.2017 11:50</date>
</server>
</dashboard>

2 个答案:

答案 0 :(得分:0)

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  //set servername
  var servername = xmlDoc.getElementsByTagName("servername");
  countServer = 0;
  for (let server of servername) {
    countServer += 1; //Here we generate the Html ID
    document.getElementById("server" + countServer).innerHTML =
      server.childNodes[0].nodeValue; //If serverX is not predefined you have to create it infront of it
  }
}

简单地循环通过可能的服务器。

此代码期望具有给定ID的html元素是预定义的,如果您没有预定义它们,您也可以在循环内生成它们。

答案 1 :(得分:0)

这应该这样做:

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var items = xmlDoc.getElementsByTagName("servername");
    var i = 1;
    for(item of items) {
        document.getElementById("server" + i).innerHTML =
        item.childNodes[0].nodeValue;
        i++;
    }
}

演示

&#13;
&#13;
var xmlString = '<dashboard>' +
'<server service="TEST">' +
    '<servername>Testserver1</servername>' +
    '<iis>OK</iis>' +
    '<fim>OK</fim>' +
    '<sql>OK</sql>' +
    '<date>19.05.2016 11:50</date>' +
'</server>' +
'<server service="TEST2">' +
    '<servername>Testserver2</servername>' +
    '<iis>OK</iis>' +
    '<fim>OK</fim>' +
    '<sql>OK</sql>' +
    '<date>18.07.2017 11:50</date>' +
'</server>' +
'<server service="TEST3">' +
    '<servername>Testserver3</servername>' +
    '<iis>NOK</iis>' +
    '<fim>NOK</fim>' +
    '<sql>OK</sql>' +
    '<date>11.02.2017 11:50</date>' +
'</server>' +
'</dashboard>';
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");

function myFunction(xml) {
    // var xmlDoc = xml.responseXML; -> We need to skip this line for our demo
    // That's because we're already passing an xmlDoc
    var items = xmlDoc.getElementsByTagName("servername");
    var i = 1;
    for(item of items) {
        document.getElementById("server" + i).innerHTML =
        item.childNodes[0].nodeValue;
        i++;
    }
}

myFunction(xmlDoc);
&#13;
<div id="server1"></div>
<div id="server2"></div>
<div id="server3"></div>
&#13;
&#13;
&#13;

(另见this JSFiddle