使用javascript将CSV文件读入数组 [英] Reading CSV file in to an array using javascript

查看:920
本文介绍了使用javascript将CSV文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些相当简单的事情,我想,但我错过了一些东西。我非常新的Javascript。我试图读取一个CSV文件到一个数组(在我的代码下面,我只是试图输出数据到警报框)。我一直收到错误访问被拒绝。

I'm trying to do something fairly simple I think but I'm missing something. I've very new to Javascript. I'm trying to read a CSV file in to an array (in my code below I'm simply trying to output the data to an alert box). I keep getting an error "access denied."

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function () {
    if(rawFile.readyState === 4) {
      if(rawFile.status === 200 || rawFile.status == 0) {
        var allText = rawFile.responseText;
        alert(allText);
      }
    }
  }
  rawFile.send(null);
}

我怀疑csv文件位于何处有问题?由于我们的CMS的限制,我只能参考这样的文件www.example.com/csvfile.csv。

I suspect there is an issue with where I have the csv file located? Due to restrictions with our CMS I can only reference the file like this www.example.com/csvfile.csv.

任何帮助将非常感激。

推荐答案

下面是将csv文件读入数组的示例代码

Here is sample code for reading csv file into array

var request = new XMLHttpRequest();  
request.open("GET", url, false);   
request.send(null);  

var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
  csvData.push(jsonObject[i].split(','));
}
// Retrived data from csv file content
console.log(csvData);

这里是工作的小提琴示例: http://jsfiddle.net/BdCnm/450/

Here is the working fiddle example: http://jsfiddle.net/BdCnm/450/

这篇关于使用javascript将CSV文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆