Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

html - Javascript readin txt file into chart

I really need some help to figure this out...

I have found a code which plot a chart out of values he gets from a website. This is close what I would like to achieve. But I dont want to get the values from the website but from a txt file.

I read that I should use json strings to convert it, but I'm not a programmer so I don't understand how to do such thing.

At the end of my question I have the code that get its value from the internet.

The txt file needs for now to be just easy like: [[0, 7], [1, 12], [2, 7], [3, 3], [4, 0], [5, 4]]

The code

<!DOCTYPE HTML>
<html>
<head>
<script>
//chart
window.onload = function() {

  var dataPoints = [];

  var chart = new CanvasJS.Chart("chartContainer", {
    theme: "light2",
    title: {
      text: "Live Data"
    },
    data: [{
      type: "line",
      dataPoints: dataPoints
    }]
  });
  updateData();

  // Initial Values
  var xValue = 0;
  var yValue = 10;
  var newDataCount = 6;

  function addData(data) {
    if (newDataCount != 1) {
      $.each(data, function(key, value) {
        dataPoints.push({
          x: value[0],
          y: parseInt(value[1])
        });
        xValue++;
        yValue = parseInt(value[1]);
      });
    } else {
      //dataPoints.shift();
      dataPoints.push({
        x: data[0][0],
        y: parseInt(data[0][1])
      });
      xValue++;
      yValue = parseInt(data[0][1]);
    }

    newDataCount = 1;
    chart.render();
    setTimeout(updateData, 1500);
  }
  function updateData() {
    $.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=" + xValue + "&ystart=" + yValue + "&length=" + newDataCount + "type=json", addData);
  }

}


</script>
</head>
<body>

<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
</body>
</html>
question from:https://stackoverflow.com/questions/65864814/javascript-readin-txt-file-into-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add the URL for the text file containing the JSON into the updateData function found in your code, replacing "https://www.mywebsite/thetextfile.txt" in the example below with the URL to your text file.

function updateData() {
    $.getJSON("https://www.mywebsite/thetextfile.txt", addData);
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...