【问题标题】:how to read csv file using jquery and print data into an array如何使用 jquery 读取 csv 文件并将数据打印到数组中
【发布时间】:2020-10-19 06:56:47
【问题描述】:

我有一个这样的 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
        });
    } );

【问题讨论】:

    标签: javascript jquery autocomplete autosuggest


    【解决方案1】:

    试试这个代码

    /* 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])
    }

    【讨论】:

    • 如何只接收输入值的id? @疼痛
    • 你的意思是1140, 1142, 1144, 1148?将line => line.split(',')[1] 替换为line => line.split(',')[0]
    • 我的意思是在自动完成时它会显示ABCD, ABDC,但它的隐藏值将是他们提到的值,你明白吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2011-12-13
    相关资源
    最近更新 更多