如何使用 jquery 读取 csv 文件并将数据打印到数组中

how to read csv file using jquery and print data into an array

我有一个这样的 csv 文件:

tags.csv

1140,ABCD
1142,ACBD
1144,ADCB
1148,DABC

想要使用 jQuery 读取此 csv 文件并打印到数组中以将此数据输入自动建议:

   $( function() {
        var availableTags = ["ABCD","ACBD","ADCB","DABC",]; //want to print csv data into this array.
        $( "#tags" ).autocomplete({
        source: availableTags
        });
    } );

试试这个代码

/* this function reads data from a file */

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "tags.csv",
        dataType: "text",
        success: function(data) { 
            const parsedCSV = parseCSV(data) 
            $( function() {
                var availableTags = parsedCSV;
                $( "#tags" ).autocomplete({
                 source: availableTags
               });
             } );
      }
     })
})

function parseCSV(csv) {
    /* split the data into array of lines of type */
    const csvLines = csv.split(/\r\n|\n/);
    /* loop throw all the lines a remove first part (from the start, to comma) */
    return csvLines.map(line => line.split(',')[1])
}