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



我有一个这样的csv文件:

标签.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(/rn|n/);
/* loop throw all the lines a remove first part (from the start, to comma) */
return csvLines.map(line => line.split(',')[1])
}

最新更新