在JavaScript中读取CSV文件

Reading CSV file in JavaScript

本文关键字:CSV 文件 读取 JavaScript      更新时间:2023-09-26

我不知道为什么它不起作用。我是这个领域的新手。我也保存了一个文件data.csv,但是没有显示。

 <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Graph</title>
 <script type="text/javascript"src="http://ajax.googleapis.com
 /ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
$(document).ready(function(){

var options = {
chart: {
    renderTo: 'container',
    defaultSeriesType: 'column'
},
title: {
    text: 'Fruit Consumption'
},
xAxis: {
    categories: []
},
yAxis: {
    title: {
        text: 'Units'
    }
},
series: []
};
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split(''n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
    var items = line.split(',');
    // header line containes categories
    if (lineNo === 0) {
        $.each(items, function(itemNo, item) {
            if (itemNo > 0) options.xAxis.categories.push(item);
        });
    }
    // the rest of the lines contain data with their name in the first position
    else {
        var series = {
            data: []
        };
        $.each(items, function(itemNo, item) {
            if (itemNo === 0) {
                series.name = item;
            } else {
                series.data.push(parseFloat(item));
            }
        });
        options.series.push(series);
    }
});
// Create the chart
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>

2。我的data.csv文件如下所示:

            Apples,Pears,Oranges,Bananas,Plums
            John,8,4,6,5
            Jane,3,4,2,3
            Joe,86,76,79,77
            Janet,3,16,13,15

我想生成交互式图形,从另一个密码保护网站(我知道密码)上的Excel文件中获取数据,但这些文件会随着时间的推移而更新。

get请求是异步的,您将其视为同步的。

在Ajax调用返回之前,var chart = new Highcharts.Chart(options);行正在运行。

您需要在加载数据后初始化图表。[在回调中]

同样在上面的代码中,我没有看到highcharts的JavaScript文件。这也是一个大问题。