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
152 views
in Technique[技术] by (71.8m points)

html - Javascript reading txt file

I have found some code where I can make a javascript chart with.The values are loaded from a website. But now I want to load the values from a local txt file like: :C:UsersOneDriveBureaubladCha

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() {
var rawFile = new XMLHttpRequest();
    rawFile.open("GET", "file:///C:Users
ickvOneDriveBureaubladChaest.txt", false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                addData(allText);
            }
        }
    }
}
  }

}


</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>

But I want it to use a local txt file.

In the txt file : [[0, 7], [1, 12], [2, 7], [3, 3], [4, 0], [5, 4]]

Anyone knows how to do this

question from:https://stackoverflow.com/questions/65868497/javascript-reading-txt-file

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

1 Reply

0 votes
by (71.8m points)

Change path of the file. $.getJSON("https://www.mywebsite/thetextfile.txt", addData); to $.getJSON("C:UsersOneDriveBureaubladCha.txt", addData);.


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

...