这里有一个类似的问题,你一定错过了。
该CSV
库解析CSV
字符串而不是文件。它给你一个空数组的原因
是因为它不完整CSV
,即至少 1 个标题 + 1 个项目。
这是源代码中的文档。
LINE 673
/**
* $.csv.toObjects(csv)
* Converts a CSV string to a javascript object.
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
...
**/
正如评论中所指出的CSV
,在浏览器中处理像这样大的文件
并不是一个明智的决定,最好在服务器上完成。
这是您可以打开文件并处理内容的一种方法。
注意:它仅适用于Firefox。IE 8Three.js
中的库阻塞。它抱怨
语法错误(??)。你会得到一个
with Opera。
Uncaught exception: DOMException: NETWORK_ERR
此外,由于在Firefox 19.0.2syntax error
中解析无效(非)XML
(即CSV
内容),您会得到一个。
这不是最优雅的解决方案。它只是工作。
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testing CSV with jQuery csv.0.71</title>
<meta charset = "utf-8">
<script src = "./three.min.js"></script>
<script src = "./jquery-2.1.0.min.js"></script>
<script src = "./stats.min.js"></script>
<script src = "./jquery.csv-0.71.js"></script>
<script>
function openCSVFile(CSVfileName){
// create the object
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
processCSVContents(httpRequest);
}
// Send the request
httpRequest.open("POST", CSVfileName, true);
httpRequest.send(null);
}
function processCSVContents(httpRequest){
console.log("--> here");
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200)
|| (httpRequest.status == 0)){
// Analys the contents using the stats library
// and display the results
CSVContents = httpRequest.responseText;
console.log($.csv.toObjects(CSVContents));
console.log(" => Response status: " + httpRequest.status)
console.log(CSVContents);
} else {
alert(' => There was a problem with the request. '
+ httpRequest.status + httpRequest.responseText);
}
}
}
</script>
</head>
<body>
<button type="button" onclick="openCSVFile('pets.csv');">Click Me!</button>
</body>
</html>
CSV
文件pets.csv包含以下内容:
name,age,weight,species
"fluffy",3,14,"cat"
"vesuvius",6,23,"fish"
"rex",5,34,"dog"
输出:
[{
name: "fluffy",
age: "3",
weight: "14",
species: "cat"
}, {
name: "vesuvius",
age: "6",
weight: "23",
species: "fish"
}, {
name: "rex",
age: "5",
weight: "34",
species: "dog"
}]
还有另一种在本地读取文件的方法,通过HTML5 的 File API