在javascript中读取本地csv文档?

[编辑]我用 D3

解决了这个问题,谢天谢地!

所以我有一个看起来像这样的csv文档,我需要将本地csv文档导入到我的客户端javascript:

"L.Name", "F.Name", "Gender", "School Type", "Subjects"
    "Doe",    "John",  "M",      "University",  "Chem I, statistics, English, Anatomy"
    "Tan",    "Betty",   "F",     "High School", "Algebra I, chem I, English 101"
    "Han",    "Anna",    "F",     "University",  "PHY 3, Calc 2, anatomy I, spanish 101"
    "Hawk",   "Alan",    "M",     "University",  "English 101, chem I"

我最终需要解析它并输出如下内容:

Chem I: 3         (number of people taking each subject)
Spanish 101: 1 
Philosophy 204: 0

但就目前而言,我只是坚持将其导入javascript.

我当前的代码如下所示:

<!DOCTYPE html>  
<html>  
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/> 
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
    var splitResearchArea = []; 
    var textInput = document.getElementById('numb').value; 
    var splitTextInput = textInput.split(",");

  for(var i =0; i<splitTextInput.length; i++) {
    var spltResearchArea = splitTextInput[i];
    splitResearchArea.push(spltResearchArea);
  }
}

我已经研究过,并在Stackoverflow上找到了一些有用的链接,如 this , thisthis ,但我是javascript的新手,我并不完全理解它.我应该使用Ajax吗?的FileReader? jQuery的?使用一个优于另一个有什么好处?你将如何在代码中实现这一点?

但是,是的,我只是困惑,因为我对javascript很新,所以任何正确方向的帮助都会很棒.谢谢!!

以下是如何使用 FileReader

API中的readAsBinaryString()来加载本地文档.

<p>Select local CSV File:</p>
<input id="csv" type="file">

<output id="out">
    file contents will appear here
</output>

基本上,只需要在<input type =“file”>中收听改变事件.并调用readFile函数.

var fileInput = document.getElementById("csv"),

    readFile = function () {
        var reader = new FileReader();
        reader.onload = function () {
            document.getElementById('out').innerHTML = reader.result;
        };
        // start reading the file. When it is done, calls the onload event defined above.
        reader.readAsBinaryString(fileInput.files[0]);
    };

fileInput.addEventListener('change', readFile);

jsFiddle

翻译自:https://stackoverflow.com/questions/29393064/reading-in-a-local-csv-file-in-javascript