From c255e1ce1cb0d3b2661afb3a25a33e55e65553c3 Mon Sep 17 00:00:00 2001 From: hodasemi Date: Mon, 22 Oct 2018 10:17:57 +0200 Subject: [PATCH] Read csv file automatically --- index.html | 2 +- main.js | 38 ++++++++++---------------------------- 2 files changed, 11 insertions(+), 29 deletions(-) diff --git a/index.html b/index.html index aed73ed..1d7fee1 100644 --- a/index.html +++ b/index.html @@ -27,7 +27,7 @@
diff --git a/main.js b/main.js index 92de276..c5aa83c 100644 --- a/main.js +++ b/main.js @@ -1,36 +1,24 @@ // Source: https://blog.mounirmesselmeni.de/2012/11/20/reading-csv-file-with-javascript-and-html5-file-api/ // Source: https://www.js-tutorials.com/javascript-tutorial/reading-csv-file-using-javascript-html5/ +// Source: https://stackoverflow.com/questions/13329853/reading-server-file-with-javascript -function handleFile(path) { +function handleFile() { // Check for the various File API support. if (window.FileReader) { // FileReader are supported. - - getAsText(file); + var xmlhttp = new XMLHttpRequest(); + xmlhttp.onreadystatechange = function () { + if (xmlhttp.status == 200 && xmlhttp.readyState == 4) { + processData(xmlhttp.responseText); + } + }; + xmlhttp.open("GET", "world_data_v1.csv", true); + xmlhttp.send(); } else { alert('FileReader are not supported in this browser.'); } } -function getAsText(fileToRead) { - var reader = new FileReader(); - - // Read file into memory as UTF-8 - - // TODO: fileToRead is the path to the file -> create a file handle - - reader.readAsText(fileToRead); - - // Handle errors load - reader.onload = loadHandler; - reader.onerror = errorHandler; -} - -function loadHandler(event) { - var csv = event.target.result; - processData(csv); -} - function processData(csv) { var table = ""; var allTextLines = csv.split(/\r\n|\n/); @@ -53,9 +41,3 @@ function processData(csv) { document.getElementById('table_bla').innerHTML = table; } - -function errorHandler(evt) { - if (evt.target.error.name == "NotReadableError") { - alert("Canno't read file !"); - } -}