如何在jQuery中加载第二个CSV?

时间:2011-09-11 10:15:19

标签: jquery

我有来自highcharts的以下代码段

    $(function() {
        $.get('trades.csv', function(csv, state, xhr) {

            // inconsistency
            if (typeof csv != 'string') {
                csv = xhr.responseText;
            }

            // parse the CSV trades
            var trades = [], header, comment = /^#/, x;

            $.each(csv.split('\n'), function(i, line){
                if (!comment.test(line)) {
                    if (!header) {
                        header = line;
                    }
                    else {
                        var point = line.split(';'),
                            date = point[0].split('-');
                            time = point[1].split(':');

                        if (point.length > 1) {
                            x = Date.UTC(date[2], date[1] - 1, date[0], time[2], time[1], time[0]);

                            trades.push([
                                x, // time
                                parseFloat(point[2]) // close
                            ]);
                        }
                    }
                }

            });

假设我希望将第二个spread.csv加载到 var spread = ...

我尝试使用适当的修改再次粘贴$ .get,但页面不再加载。加载第二个CSV的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

function getCsv(file_name, array_holder){
    $.get(file_name, function(csv, state, xhr) {

        // inconsistency
        if (typeof csv != 'string') {
            csv = xhr.responseText;
        }

        // parse the CSV trades
        var header, comment = /^#/, x;

        $.each(csv.split('\n'), function(i, line){
            if (!comment.test(line)) {
                if (!header) {
                    header = line;
                }
                else {
                    var point = line.split(';'),
                        date = point[0].split('-'),
                        time = point[1].split(':');

                    if (point.length > 1) {
                        x = Date.UTC(date[2], date[1] - 1, date[0], time[2], time[1], time[0]);

                        array_holder.push([
                            x, // time
                            parseFloat(point[2]) // close
                        ]);
                    }
                }
            }

        });
    });
}

$(function() {
    var trades  = [],
        spreads = [];
    getCsv('trades.csv', trades);
    getCsv('spreads.csv', spreads);

});