使用csv中的解析文本定义变量的简单方法?

时间:2017-04-17 22:21:16

标签: javascript jquery ajax

我试图在JavaScript中使用switch语句来确定来自外部serverlist.csv的服务器状态。如果csv读取“online”,则switch语句显示success.svg,如果“offline”,则switch语句显示error.svg,等等。

在switch语句中,我尝试使用从外部csv报告中提取的信息定义变量:

<p id="demo"></p>

<script>
function myFunction() {
    var online = "online"
    var offline = "offline"
    var waiting = "waiting"
      var x;
    var y;
    var d = /* outcome of this variable will be extracted from serverlist.csv, but manually enter value here for now */ online;

    switch (d) {
        case 'waiting':
            x = "Waiting...";
            y = 'waiting';
            break;
        case 'online':
            x = "Online!";
            y = 'success';
            break;
        case 'offline':
            x = "Offline!";
            y = 'error';
            break;
    }
    document.getElementById("demo").innerHTML = x;
    document.getElementById(y).style.display = 'block';
}

window.onload = myFunction;
</script>

<img src="https://image.flaticon.com/icons/svg/130/130879.svg" id="success" style="display:none; width: 100px; height: 100px;"/>
<img src="https://image.flaticon.com/icons/svg/130/130877.svg" id="error" style="display:none; width: 100px; height: 100px;"/>
<img src="https://image.flaticon.com/icons/svg/130/130920.svg" id="waiting" style="display:none; width: 100px; height: 100px;"/>

https://jsfiddle.net/6o5dLfne/4/

Here is the serverlist.csv

1 个答案:

答案 0 :(得分:1)

我只是将服务器状态放入一个数组中,而不是很容易用它来操作:

&#13;
&#13;
var response = 'Server,Status\n\
Server1,Online\n\
Server2,Offline\n\
';
var lines = response.split('\n');
var servers = [];
$.each(lines, function(l, line) {
	if( l && line ) {
    	var status = line.split(',');
        servers.push({
        	'name': status[0],
            'status': status[1]
        })
    };
});
var demo = $('#demo');
var demoHtml = '';
$.each(servers, function(s, server) {
	demoHtml += '<p class="server-status server-' + server.status + '">' + server.name + '</p>\n'
});
demo.html( demoHtml );
&#13;
.server-status::after {
    content: '';
    display: inline-block;
    margin-left: 5px;
    width: 20px;
    height: 20px;
    background-position: center;
    background-size: 20px auto;
}
.server-Online::after {
    background-image: url('https://image.flaticon.com/icons/svg/130/130879.svg');
}
.server-Offline::after {
    background-image: url('https://image.flaticon.com/icons/svg/130/130877.svg');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This demo is attempting to test out the functionality of switching images depending on server status from an external .csv report that will be generated from a powershell script. The goal is to build a responsive webpage dashboard.</p>

<div id="demo"></div>
&#13;
&#13;
&#13;

请注意,使用CSS控制布局更容易,如上所述。此外,对于此类应用和类似应用,您可以考虑使用Knockout框架,看一下实现的简单程度here

JSFiddle上的示例。