2

I am trying to import a csv-list of email addresses to a form field with jQuery-csv... Everything works fine but for some strange reason, the array is always missing out the last item (in this case it is: 'adress-6@test.com').

My jQuery:

function process_csv() {

// The event listener for the file upload
document.getElementById('txtFileUpload').addEventListener('change', upload, false);

// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
    var isCompatible = false;
    if (window.File && window.FileReader && window.FileList && window.Blob) {
    isCompatible = true;
    }
    return isCompatible;
}

// Method that reads and processes the selected file
function upload(evt) {
if (!browserSupportFileUpload()) {
    alert('The File APIs are not fully supported in this browser!');
    } else {
        var data = null;
        var files = evt.target.files;
        var file = files[0];
        var reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function(event) {
            var csv = event.target.result;
            console.log(csv);
            var data = jQuery.csv.toArrays(csv);
            console.log(data);
            if (data && data.length > 0) {
              alert('Imported -' + data.length + '- rows successfully!');

              var output = '';

              for(var row in data){
                for (var item in data[row]){
                    output += data[row][item] + ', ';
                }
              }
              console.log(output);

            } else {
                alert('No data to import!');
            }
            $("input#field_50euu").val( output );
        };
        reader.onerror = function() {
            alert('Unable to read ' + file.fileName);
        };
    }
}
};

I logged the values to the console, step-by-step. This is what I get:

[Log] adress-1@test.com
adress-2@test.com
adress-3@test.com
adress-4@test.com
adress-5@test.com
adress-6@test.com (mandanteninformation.js, line 28)

[Log] [["adress-1@test.com"], ["adress-2@test.com"], ["adress-3@test.com"], ["adress-4@test.com"], ["adress-5@test.com"]] (5) (mandanteninformation.js, line 30)

[Log] adress-1@test.com, adress-2@test.com, adress-3@test.com, adress-4@test.com, adress-5@test.com,  (mandanteninformation.js, line 41)

When I edit my csv-file and add an empty line at the end, I get all adresses.

Can anyone tell me, what is wrong with my function? I did not find anything on the internet about it.

Thank you!

4

1 回答 1

0

我可以毫无问题地让您的代码(经过一些小的修改,包括外部文件)输出一个末尾没有空行的小 CSV 文件的所有行。

作为测试,我创建了这个 CSV 文件:

Col1,Col2,Col3
1,A,Red
2,B,Yellow
3,C,Blue

然后使用这个jsfiddle上传它,导致显示 CSV 文件的所有四行的警报。

请测试并回复您的结果。也许问题在于您的 CSV 文件,而不是您的代码。

于 2016-09-21T14:59:34.510 回答