JavaScript for everyone with table

I’m writing a Javascript application that gets some text from an xml file and displays it in a html table. Here’s the code that i have for this task:

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;
}

How can i change this function to execute a variable number of servernames in the xml file?

Thank you very much for your help!

XML File:


    Testserver1
    OK
    OK
    OK
    18.07.2017 11:50


    Testserver2
    OK
    OK
    OK
    18.07.2017 11:50

This should do it :

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++;
    }
}

Demo

var xmlString = '' +
'' +
    'Testserver1' +
    'OK' +
    'OK' +
    'OK' +
    '19.05.2016 11:50' +
'' +
'' +
    'Testserver2' +
    'OK' +
    'OK' +
    'OK' +
    '18.07.2017 11:50' +
'' +
'' +
    'Testserver3' +
    'NOK' +
    'NOK' +
    'OK' +
    '11.02.2017 11:50' +
'' +
'';
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);

(See also
this JSFiddle

)

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » JavaScript for everyone with table

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录