javascript canvasjs从file.txt动态获取数据点

时间:2017-02-15 19:12:49

标签: canvasjs

目标:

我想从file.txt获取数据,这些数据在本地保存在/var/www/html/file.txt中,并以2秒的间隔动态地用于我网页上的圆环图

file.txt只有一个条目,如下所示:

34

我试过的javascript:

$.get("file.txt", function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
    for(var i=0; i< allLines.length; i++) {
        dataPoints.push({y: parseInt(allLines[i])});
        x += .25;
    }
}
var chart = new CanvasJS.Chart("chartContainer",{
    title :{
        text: "Chart using Text File Data"
    },
    data: [{
        type: "doughnut",
        dataPoints : dataPoints,
    }]
});
chart.render();
});
}

整个html看起来像

<!DOCTYPE html>
<html>
<head>
  <title>Chart using txtfile Data</title>
  <script type="text/javascript" src="http://canvasjs.com/assets/script            /jquery-1.11.1.min.js"></script>
  <script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
 <script type="text/javascript">
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var chart = new CanvasJS.Chart("chartContainer",{
    title :{
        text: "Chart using Text File Data"
    },
    data: [{
        type: "line",
        dataPoints : [function()
        {
        if(allLines.length > 0) {
           for(var i=0; i< allLines.length; i++) {
           xVal +=.25;
           dataPoints.push({x : xVal, y: parseInt(allLines[i])});
    }
}
}]
    }]
});
chart.render();
},'text');
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我相信这样的事可能适合你。您可能必须使用Firefox,因为Chrome不喜欢跨源请求

首先,dataPoints未定义,我将代码移动到dataPoints中的函数中。我将变量名称从x更改为xVal。添加了'text'字样,以便$ get知道它正在阅读的格式,并且还有一个额外的括号。试一试。

    $.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var dps = [];

for(var i=0; i< allLines.length; i++) {
   xVal +=.25;
   dps.push({x : xVal, y: Number(allLines[i])});
}

var chart = new CanvasJS.Chart("chartContainer",{
    title :{
        text: "Chart using Text File Data"
    },
    data: [{
        type: "line",
        dataPoints : dps
    }]
});
chart.render();
},'text');