0

I'm using this code to import a CSV into a var using ajax, then, split the informatión delimited by the "\n" and then populate a Select Box I have in a form.

The CSV is pretty much flat, just 1 column with several rows. Added an alert to monitor the progress.. it all goes fine except when it comes to populate the combobox, instead of populating the String Content, it populates the number of row, for some reason the array is not recording string but row number.

<script>
$.ajax({
    url: 'URL CSV',
    success: function(data) {

        alert(data);

        var splitData=data.split("\n");

        for(pn in splitData){

            alert(splitData);

            $('#Entry_ID').append("<option value=\""+pn+"\">"+pn+"</option>");
        }
    }
});
</script>

(the form combobox code)

<select name="Entry.ID" id="Entry_ID" aria-required="true"></option>
</select>
4

1 回答 1

0

您的错误在“for..in”循环中。像这样的代码:

var arr = ["q", "w", "e"];
for (var i in arr) {
    console.log(i)
}

将输出:

0
1
2

for..in 循环获取对象中每个项目的键并将其分配给 var。在数组中,键是它的位置。

String 的方法 split 返回一个包含所有项目的数组。要遍历 splitData 数组,您可以:

for (var i = 0; i < splitData.length; i++) {
    alert(splitData[i]);
    $('#Entry_ID').append("<option value=\"" + splitData[i] + "\">" +
        splitData[i] + "</option>");
}

或者

splitData.forEach(function (item) {
    alert(item);
    $('#Entry_ID').append("<option value=\"" + item + "\">" + item + "</option>");
});
于 2013-06-16T17:34:51.657 回答